Blankman - 1 year ago 49

Ruby Question

How can I grab the value 3 from "Page 1 of 3" given the below text:

`Displaying Results Items 1 - 50 of 120, Page 1 of 3`

If someone can briefly explain the regex that would be helpful.

Answer Source

Regular Expression you need consists of a `+`

quantifier (one or more times - greedy), a numerical character class `[0-9]`

and a capturing group `(...)`

.

```
str = "Displaying Results Items 1 - 50 of 120, Page 1 of 3"
print str.match(/Page +[0-9]+ +of +([0-9]+)/)[1]
```

Explanation:

```
Page + # Match `Page` and any number of spaces (one or more)
[0-9]+ # Then any number of digits (one or more)
+of # Then any number of spaces (one or more) followed by `of`
+ # Then any number of spaces (one or more)
([0-9]+) # Finally up to another sequence of digits - captured by constructing a capturing group
```

There is a good reference here as well as Documentation to learn more about RegExes.