Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Non-greedy regex behaves greedily

by busunsl (Vicar)
on Nov 10, 2004 at 12:09 UTC ( #406654=note: print w/ replies, xml ) Need Help??


in reply to Non-greedy regex behaves greedily

Because you insist on a character after 'body' that isn't there when you use '.+?'.

Change it to s/<body.*?>/<body class="theBody">/ and it will work.


Comment on Re: Non-greedy regex behaves greedily
Download Code
Re^2: Non-greedy regex behaves greedily
by fourmi (Scribe) on Nov 10, 2004 at 12:19 UTC
    Oh ok, i always went with .+? as an antigreedifier, had assumed that the ? made the .+ optional..

    That works though, but is does that mean that my antigreedifier ideas are wrong?
      Yes, yes it does.

      ? doesn't make it any more or less optional, just non-greedy.

      It means the belief that "antigreedifier" make the aforementioned "at least one or more" optional is wrong.

      "at least one or more" /.+/ still proves wrong if there is nothing.

      Cheers, Sören

      Possibly, I don't know what your exact ideas are :-) At least .+? is not an optional match for one or more things.

      But I've also noticed that a lot of people use non-greedy matching as if it's some sort of magical negative lookahead. It isn't. It will do whatever it takes to match, even if that means also eating one or more of the character(s) that directly follows the non-greedy match (and exiting the repeat at some later instance of that character(s) instead). If your regex has only one match of a non-fixed length you can usually get away with this, but especially if there are more than one them, the semantics can get unexpected.

      If you don't want to match something, it's almost always better to just say that. So in your case that would be:

      s/<body[^>]+>/.../
      (also notice that greedy or non-greedy becomes irrelevant if you write it like this) It would of course still not work as expected (the + should be a * since matching 0 times should be allowed too), but at least the problem now will be not doing anything at all instead of changing too much. And it will keep working as expected even if you make your regex more complicated.
        ok, today i learned something interesting for a change!

        Thanks for the assistances!!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (14)
As of 2014-12-18 20:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (61 votes), past polls