http://qs321.pair.com?node_id=406654


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.

Replies are listed 'Best First'.
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?
      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!!
      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