in reply to Why isn't this regex greedy?

The ((?!bar).){1,5} says match any sequence of characters of up to 5 characters so long as no part of those 5 characters is part of a "bar" string. It will match the most of those chars (up to the max) that it can, which means it is greedy. The zero width assertion prevents the greedyness from overruning. Its pretty well the same thing as:

/(foo)(.{1,5}?)bar/

Except I'd expect the latter to be more efficient.

---
$world=~s/war/peace/g

Replies are listed 'Best First'.
Lazy vs Inchworm (was: Re^2: Why isn't this regex greedy?)
by merlyn (Sage) on Mar 17, 2006 at 14:40 UTC
    Its pretty well the same thing as
    Well, you might want to point out how it's different. Laziness is a tendency, not a mandate. Adding a trailing "Q" to both regex shows the difference:
    "fooXbarYbarQ" =~ /(foo)(.{1,5}?)barQ/ # match entire string
    will match, skipping over the first bar because it's not followed by Q. However, the previous regex, followed by a Q will fail:
    "fooXbarYbarQ" =~ /(foo)(((?!bar).){1,5})barQ/ # won't match
    because it can't "skip over" the first bar to get to the second one.

    So, while lazy is good, it's not the only game in town, and you have to consider the rest of the regex before you know you can get away with lazy instead of inchworm.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re^2: Why isn't this regex greedy?
by Melly (Chaplain) on Mar 17, 2006 at 10:20 UTC

    Aha!

    I thought it must be something like that - the issue that I was uncertain about what was what the neg-lookahead was applied to. It would seem it applies to the .{1,5} rather than the 'foo'.

    Slightly non-intuitive IMHO, but I've got it now...

    Tom Melly, tom@tomandlu.co.uk

      "Lookahead" implies "characters following", if it was "lookbehind" it would be "characters preceding". "negative lookahead" means that the following characters can not match. "Negative lookbehind" would mean that the preceding characters can not match.

      ---
      $world=~s/war/peace/g