Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Regex (counting) confusion :(

by fletcher_the_dog (Friar)
on Sep 18, 2003 at 14:25 UTC ( [id://292399]=note: print w/replies, xml ) Need Help??


in reply to Regex (counting) confusion :(

The 2 comes from the fact that "x*" can match nothing. For "xxxx", "x*" matches the null width "beginning" then matches all the "x"s to the end. The 9 is because of the non-greediness, so you get a match at the null-width beginning, at each character, between each character, and the end.
UPDATE: I ran your original code using "use re 'debug'" and it looks like when you get 2 it is actually matching the "xxxx" and then the end not the beginning.

Replies are listed 'Best First'.
Re: Regex (counting) confusion :(
by Abigail-II (Bishop) on Sep 18, 2003 at 14:40 UTC
    For "xxxx", "x*" matches the null width "beginning" then matches all the "x"s to the end.

    Well, that would mean the first result would be 1, not 2. What happens is that /x*/ matches the zero-length string at the beginning, all the x-es, but not the zero-length string at the end. After the first substitution, the regex hasn't reached the end of the string yet, so /g kicks in. All that's left is the zero-width string at the end - this is now matched (were it wasn't before), and hence we get a second substitution, resulting in a result of 2 and a final "##" string.

    Frankly, I find this behaviour unexpected and unwanted. I'd call it a bug, but I bet someone once had a use for this, and now that's the way it goes.

    Abigail

      That's what I was looking for. Danke schoen!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://292399]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-19 12:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found