From: "Wesley J. Landaker" Date: 2003-08-27T04:29:22+09:00 Subject: Named matches for regular expressions (was: Re: Specification of Ruby regex?) Apparently, Austin Ziegler recently wrote: > On Tue, 26 Aug 2003 21:28:07 +0900, Gavin Sinclair wrote: >> On Tuesday, August 26, 2003, 10:18:24 PM, Emmanuel wrote: >>> btw, since there is a thread about that, i wanted to ask: does ruby >>> support named matches (sorry i don't know the proper terminology)? C# >>> does it like this: "(?\d{4})-(?\d{1,2})-(?\d{1,2})" >>> matches "2002-4-6" >>> and then in my match groups i have "year", "month", "day". >>> (looked in pickaxe + google ruby "regexp match group") >> I'm 99.99% sure it doesn't. > > The latest Oniguruma supports it. I'm not sure how to use/enable that, but > it does support it. Something like this? class NamedMatchRegex def initialize(regex) regex_string = regex.inspect @match_names = ["MATCH"] regex_string.gsub!(/\?:<[^>]+>/) { |match| name = match[3..-2] @match_names << name "" } @regex = eval regex_string end def match(string) match_data = @regex.match(string) return nil if match_data.nil? match_data = match_data.to_a named_match_data = {} @match_names.each { |name| named_match_data[name] = match_data.shift } named_match_data end end irb(main):001:0> load 'test.rb' => true irb(main):002:0> re = /^\s*(?:\d+)\s*(?:\w+).*$/ => /^\s*(?:\d+)\s*(?:\w+).*$/ irb(main):003:0> string = " 12345678 we thing ruby is really great" => " 12345678 we thing ruby is really great" irb(main):004:0> re.match(string) => nil irb(main):005:0> nmre = NamedMatchRegex.new(re) => # irb(main):006:0> matches = nmre.match(string) => {"number"=>"12345678", "word"=>"we", "MATCH"=>" 12345678 we thing ruby is really great"} irb(main):007:0> matches["MATCH"] => " 12345678 we thing ruby is really great" irb(main):008:0> matches["number"] => "12345678" irb(main):009:0> matches["word"] => "we" irb(main):010:0> Obviously this isn't complete, I just whipped it up to respond to this message. =) Wes