From: "David A. Black" Date: 2005-04-01T06:06:51+09:00 Subject: Re: Regex parsing question Hi -- On Fri, 1 Apr 2005, 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= > > Instead of: > > $1=AA > $2=BBCCDDEE > $3= > $4= Because * is "greedy" -- meaning, it eats up as many characters as possible, from left to right, while still allowing for a successful match overall. So your first .* eats up everything until it reaches as far right as it possibly can -- namely, just before the second (which it then leaves intact so that it can be matched by the literal in your regex). It even eats up the first . > And how would I fix it? Use *? instead of * -- like this: regex = %r{(.*?)(.*)} David -- David A. Black dblack@wobblini.net