您需要使用.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