mlzboy mlzboy - 1 year ago 72
Ruby Question

Regex with named capture groups getting all matches in Ruby

I have a string:


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


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

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download