in reply to regex negative lookahead behaviour

The problem is that whilst \s* is greedy, it will also match zero spaces, which means that '1/2' followed by zero spaces is not followed by 'MILE', because it is followed by ' MILE' which satisfies the condition, so the expression is true.

The only thing that overrides a regexes natural greediness is it's desire to achieve a match. If it can, it will, and it can, so it does:)


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller

Replies are listed 'Best First'.
Re: Re: regex negative lookahead behaviour
by pijll (Beadle) on Jul 19, 2003 at 11:49 UTC
    The only thing that overrides a regexes natural greediness is it's desire to achieve a match.
    Normal regexes are greedy, but not selfish; they are willing to give characters back if it's for the greater good.

    But you can use the (?>pattern) construct to create "selfish" regexes: they only try to match once at every position. If the pattern inside is greedy, it will never give up chars to make the entire regex match; if the pattern is lazy, it will never match more than the absolute minimum of chars at that position.

    So "1/2 MILE" =~ m[1/2(?>\s*)(?!MILE)] should work.