mlzboy mlzboy - 3 months ago 15
Ruby Question

Regex with named capture groups getting all matches in Ruby

I have a string:

s="123--abc,123--abc,123--abc"


I tried using Ruby 1.9's new feature "named groups" to fetch all named group info:

/(?<number>\d*)--(?<chars>\s*)/


Is there an API like Python's
findall
which returns a
matchdata
collection? In this case I need to return two matches, because
123
and
abc
repeat twice. Each match data contains of detail of each named capture info so I can use
m['number']
to get the match value.

Answer

Named captures are suitable only for one matching result.
Ruby's analogue of findall is String#scan. You can either use scan result as an array, or pass a block to it:

irb> s = "123--abc,123--abc,123--abc"
=> "123--abc,123--abc,123--abc"

irb> s.scan(/(\d*)--([a-z]*)/)
=> [["123", "abc"], ["123", "abc"], ["123", "abc"]]

irb> s.scan(/(\d*)--([a-z]*)/) do |number, chars|
irb*     p [number,chars]
irb> end
["123", "abc"]
["123", "abc"]
["123", "abc"]
=> "123--abc,123--abc,123--abc"