我需要使用正则表达式获取项目总数

时间:2016-09-03 12:27:58

标签: ruby regex

如何从" Page 1 of 3"中获取值3?鉴于以下文字:

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

如果有人可以简要解释一下有用的正则表达式。

2 个答案:

答案 0 :(得分:2)

您需要的正则表达式包含[0-9]量词(一次或多次 - 贪婪),数字字符类(...)和捕获组str = "Displaying Results Items 1 - 50 of 120, Page 1 of 3" print str.match(/Page +[0-9]+ +of +([0-9]+)/)[1]

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

Live demo

说明:

{{1}}

有一个很好的reference here可以了解有关RegExes的更多信息。

答案 1 :(得分:1)

你可以做到

str.scan(/Page \d+ of (\d+)/) #=> [["3"]]

它试图匹配" Page#of#"并抓住最后一个捕获组。如果你在字符串中有相同模式的倍数,这将是有效的,它将全部是结果数组的一部分。