【问题标题】:RegExp#match returns only one matchRegExp#match 只返回一个匹配项
【发布时间】:2013-10-15 05:35:05
【问题描述】:

请解释一下,为什么match() 只返回一个匹配项,而不是四个匹配项(例如):

s = 'aaaa'
p /a/.match(s).to_a # => ["a"]

奇怪的是,分组 match() 返回两个匹配,独立于真实匹配计数:

s = 'aaaa'
p /(a)/.match(s).to_a # => ["a", "a"]

s = 'a aaa a'
p /(a)/.match(s).to_a # => ["a", "a"]

感谢您的回答。

【问题讨论】:

  • 你确定你问的是Regexp#math吗?

标签: ruby regex pcre


【解决方案1】:

您需要使用.scan() 匹配多次:

p s.scan(/a/).to_a

通过分组,你会得到一个整体匹配结果,每个组一个结果(使用.match()时。两个结果在你的正则表达式中是相同的。

一些例子:

> /(a)/.matc­h(s).to_a
=> ["a", "a"]           # First: Group 0 (overall match), second: Group 1
> /(a)+/.mat­ch(s).to_a­
=> ["aaaa", "a"]        # Regex matches entire string, group 1 matches the last a
> s.scan(/a/­).to_a
=> ["a", "a", "a", "a"] # Four matches, no groups
> s.scan(/(a­)/).to_a
=> [["a"], ["a"], ["a"], ["a"]] # Four matches, each containing one group
> s.scan(/(a­)+/).to_a
=> [["a"]]              # One match, the last match of group 1 is retained
> s.scan(/(a­+)(a)/).to­_a
=> [["aaa", "a"]]       # First group matches aaa, second group matches final a
> s.scan(/(a­)(a)/).to_­a
=> [["a", "a"], ["a", "a"]] # Two matches, both group participate once per match

【讨论】:

    【解决方案2】:

    按特征,match 只匹配一次。单个匹配对应一个MatchData 实例,MatchData#to_a 返回一个数组,其中第 0 个元素是整个匹配,其他第 n 个元素分别是第 n 个捕获。捕获是在() 中匹配的任何内容。如果您在正则表达式中没有任何 (),则该数组将只有整个匹配项。

    "a"["a", "a"]/(a)/中之所以有多个"a"是因为单个匹配除了整个匹配之外还有一个捕获:第一个"a"代表整个匹配,对应@987654330 @,第二个"a"代表第一次捕获,对应(a)里面的a

    如果您想匹配任意多个匹配项,请使用scan

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      相关资源
      最近更新 更多