-4

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.

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

2

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]

Live demo

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.

Graham
  • 7,431
  • 18
  • 59
  • 84
revo
  • 47,783
  • 14
  • 74
  • 117
1

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.

davidhu
  • 9,523
  • 6
  • 32
  • 53