[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

weird gsub behavior

Lou Zell

1/24/2008 2:44:00 AM

Hi,

I came across a problem in a gsub and boiled it down to this difference,
can anyone explain?

>> b="trying to match whole string"
=> "trying to match whole string"

>> b.gsub(/(.+)/,'MATCH:\1')
=> "MATCH:trying to match whole string"

That operated the way I expected, but:

>> b.gsub(/(.*)/,'MATCH:\1')
=> "MATCH:trying to match whole stringMATCH:"


What is with that second match?

Thanks,
Lou
--
Posted via http://www.ruby-....

3 Answers

Lou Zell

1/24/2008 3:54:00 AM

0

Anyone?

--
Posted via http://www.ruby-....

Phrogz

1/24/2008 4:01:00 AM

0

On Jan 23, 7:43 pm, Lou Zell <lzel...@gmail.com> wrote:
> Hi,
>
> I came across a problem in a gsub and boiled it down to this difference,
> can anyone explain?
>
> >> b="trying to match whole string"
>
> => "trying to match whole string"
>
> >> b.gsub(/(.+)/,'MATCH:\1')
>
> => "MATCH:trying to match whole string"
>
> That operated the way I expected, but:
>
> >> b.gsub(/(.*)/,'MATCH:\1')
>
> => "MATCH:trying to match whole stringMATCH:"

.* means "zero or more of any character (other than a newline), as
many as you can and still have the rest of the pattern match".

So first gsub tries to find this, and finds:
"trying to match whole string"
so it replaces it:
"MATCH:trying to match whole string"

Now, the 'g' in 'gsub' means 'global', so it doesn't stop after just
one match/replacement. It keeps on going through the string, finding
more things to replace. At this point, it starts looking for the
pattern again, this time starting after the 'g' in 'string'. Can it
find "zero or more of any character (other than a newline)"? Yes, it
can. It finds zero of them. So then it replaces that (empty string)
with "MATCH:", resulting in:
"MATCH:trying to match whole stringMATCH:"

Lou Zell

1/24/2008 4:12:00 AM

0

Excellent, thank you!
--
Posted via http://www.ruby-....