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


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

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.