weird gsub behavior

L

Lou Zell

Hi,

I came across a problem in a gsub and boiled it down to this difference,
can anyone explain?
=> "trying to match whole string"
=> "MATCH:trying to match whole string"

That operated the way I expected, but:
=> "MATCH:trying to match whole stringMATCH:"


What is with that second match?

Thanks,
Lou
 
P

Phrogz

Hi,

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


=> "trying to match whole string"


=> "MATCH:trying to match whole string"

That operated the way I expected, but:


=> "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:"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top