Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re^2: Non-greedy regex behaves greedily

by fourmi (Scribe)
on Nov 10, 2004 at 12:19 UTC ( #406658=note: print w/replies, xml ) Need Help??

in reply to Re: Non-greedy regex behaves greedily
in thread Non-greedy regex behaves greedily

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?
  • Comment on Re^2: Non-greedy regex behaves greedily

Replies are listed 'Best First'.
Re^3: Non-greedy regex behaves greedily
by thospel (Hermit) on Nov 10, 2004 at 12:32 UTC
    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:

    (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!!
Re^3: Non-greedy regex behaves greedily
by Jasper (Chaplain) on Nov 10, 2004 at 12:24 UTC
    Yes, yes it does.

    ? doesn't make it any more or less optional, just non-greedy.
Re^3: Non-greedy regex behaves greedily
by Happy-the-monk (Canon) on Nov 10, 2004 at 12:27 UTC

    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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2020-10-31 04:49 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (286 votes). Check out past polls.