rubyregexrubularnamed-captures

How to get Match Groups in ruby like Rubular without spliting the string


How does Rubular (Example) get the match groups?

/regex(?<named> .*)/.match('some long string')

match method (in example) only returns the first match.

scan method returns an array without named captures.

What is the best way to get an array of named captures (no splitting)?


Solution

  • I've always assumed that Rubular works something like this:

    matches = []
    
    "foobar foobaz fooqux".scan(/foo(?<named>\w+)/) do
      matches << Regexp.last_match
    end
    
    p matches
    # => [ #<MatchData "foobar" named:"bar">,
    #      #<MatchData "foobaz" named:"baz">,
    #      #<MatchData "fooqux" named:"qux"> ]
    

    If we use enum_for and $~ (an alias for Regexp.last_match) we can make it a bit more Rubyish:

    matches = "foobar foobaz fooqux".enum_for(:scan, /foo(?<named>\w+)/).map { $~ }