From: James Edward Gray II Date: 2005-04-01T06:01:56+09:00 Subject: Re: Regex parsing question On Mar 31, 2005, at 2:49 PM, Paul Hanchett wrote: > Why does this: > > text= "AABBCCDDEE" > regex = %r{(.*)(.*)} > > t = text.sub( regex, "z" ); > print "$1=#{$1}\n$2=#{$2}\n$3=#{$3}\n$4=#{$4}\n" > > Return this: > > $1=AABB > $2=CCDDEE > $3= > $4= Because the construct .* means, "Zero of more non-newline characters, but as many as I can get". We say the * operator is "greedy". > Instead of: > > $1=AA > $2=BBCCDDEE > $3= > $4= > > And how would I fix it? One way would be to switch from the greedy * to the conservative *?. That would have your Regexp looking like this: %r{(.*?)(.*)} Another way is to use split() with a limit: irb(main):001:0> text= "AABBCCDDEE" => "AABBCCDDEE" irb(main):002:0> first, rest = text.split(//, 2) => ["AA", "BBCCDDEE"] irb(main):003:0> first => "AA" irb(main):004:0> rest => "BBCCDDEE" Hope that helps. James Edward Gray II