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.
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 to learn more about RegExes.
you can do
str.scan(/Page \d+ of (\d+)/) #=> [["3"]]
It is trying to match the pattern of "Page # of #" and grabbing the last capture group. This will work if you have multiples of the same pattern in the string, it will all be a part of the resulting array.