From: Jeff Wood Date: 2005-12-15T09:16:52+09:00 Subject: Re: regular expressions question You should be able to tell who this message is meant for: PLEASE stop sending out code that uses any of the perl ${x} variables ... They are ugly and have no place in Ruby ... they are only provided to make the transition of Perl people easier ... Please teach people to use MatchData objects ... my_regex = /(\w\s*?.\s*?\w)\s*?.\s*?(\w)/ matches = my_regex.match( "a , b,c" ) element 0 of the matches object will contain the complete matched string. each element after that will map to one of the groups you defined ... so: matches[0] will be the whole string "a , b,c" matches[1] will be your first group "a , b" matches[2] will be your second group "c" ... seriously, we're not helping people make cleaner code when we show approval for the ugly/evil ${x} warts we've kept from Perl. ... show people the beauty and cleanliness of using an OOP solution ... I hope you agree. j. On 12/14/05, Ross Bamford wrote: > On Wed, 14 Dec 2005 21:59:27 -0000, ako... wrote: > > > thank you. the question is general. > > > > if i wanted to parse a list of letters separated by spaces and commas: > > > > 'a , b,c' =~ /^(?:(\w)\s*,\s*)*(\w)$/ > > > > i need to get ['a','b'] in group 1 and ['c'] in group 2. yes, i know i > > can split, then massage the result some more and get the final result. > > is there a way to get to groups' captures after a regex match? like in > > microsoft's .net? > > > > I don't really get what you mean. I don't understand the rules that got a > and b into one group and c into another. When you say it's a general > question, do you mean you just want access to the captures from some > regexp match? > > irb(main):009:0> "a , b,c" =~ /(\w\s*?,\s*?\w)\s*?,\s*?(\w)/ > => 0 > irb(main):010:0> $1 > => "a , b" > irb(main):011:0> $2 > => "c" > irb(main):012:0> $~[1] > => "a , b" > irb(main):013:0> $~[2] > => "c" > irb(main):014:0> md = /(\w\s*?,\s*?\w)\s*?,\s*?(\w)/.match("a, b,c") > => # > irb(main):015:0> md[1] > => "a, b" > irb(main):016:0> md.captures[1] > => "c" > irb(main):017:0> $~.inspect > => "#" > > (and others...) > > Hope that helps, > Ross > > -- > Ross Bamford - rosco@roscopeco.remove.co.uk > "\e[1;31mL" > > -- "Remember. Understand. Believe. Yield! -> http://ruby-lang.org" Jeff Wood