ruby - RegExp#match 只返回一个匹配项

标签 ruby regex pcre

请解释一下,为什么 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)/.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

关于ruby - RegExp#match 只返回一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19373954/

相关文章:

javascript - 匹配两个不同的规则(javascript regexp)

Java .split() 与正则表达式匹配 html <a> 链接

ruby - 使用数组中的键迭代散列,并对结果求和

ruby - 使用 Ruby Mechanize 提交 'aspnetForm' 未按预期工作

正则表达式结束字符可以是 2 个之一

regex - 如何使用 pcregrep 排除多个目录?

regex - 区分 Haskell 中的空正则表达式匹配和无匹配

regex - 在 Tcl 中实现 "quotemeta"\Q ...\E ?

mysql - 如何在 Ruby 中处理日和月?

ruby - 如何在 Ruby 正则表达式中放置转义字符(不是 "escaped"字符)?