请解释一下,为什么 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"]
感谢您的回答。
最佳答案
需要使用.scan()
进行多次匹配:
p s.scan(/a/).to_a
通过分组,整体匹配得到一个结果,每个组得到一个结果(使用 .match()
时。这两个结果在正则表达式中是相同的。
一些例子:
> /(a)/.match(s).to_a
=> ["a", "a"] # First: Group 0 (overall match), second: Group 1
> /(a)+/.match(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
关于ruby - RegExp#match 只返回一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19373954/