RegExp # match returns only one match

Please explain to me why it match()returns only one match instead of four (for example):

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

It seems that when grouping match(), two matches are returned, regardless of the actual matches:

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

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

Thank you for your responses.

+4
source share
2 answers

You need to use .scan()to match more than once:

p s.scan(/a/).to_a

And with the grouping, you get one result for a common match and one for each group (when using .match(). Both results are the same in your regular expression.

Some examples:

> /(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
+9
source

match . MatchData, MatchData#to_a , 0- , n- n- . - , (). () , .

, "a" ["a", "a"] ["a", "a"] /(a)/, , : "a" , /(a)/, "a" , a (a).

, scan.

+3

All Articles