http://www.perlmonks.org?node_id=293816


in reply to Re: Backtracking problem with .*(?!bar)
in thread Backtracking problem with .*(?!bar)

Many thanks to both of you !
This had me flummoxed for quite some time.

For my understanding:
Abigail's answer reads
Beginning of line, followed any number of times by anything that isn't preceded by "system",
follwed by an end of line marker

and BrowserUK's reads:
Beginning of line not followed by anything that is followed by "system"


In both cases, I assume that it is the presence of begin/end line qualifiers that stops the regex
from backtracking and matching any as .*(?!system) does.
Shame an Initiate can't at least cast one vote :(
  • Comment on Re: Re: Backtracking problem with .*(?!bar)

Replies are listed 'Best First'.
•Re: Re: Re: Backtracking problem with .*(?!bar)
by merlyn (Sage) on Sep 24, 2003 at 10:27 UTC
    In both cases, I assume that it is the presence of begin/end line qualifiers that stops the regex from backtracking and matching any as .*(?!system) does.
    No, they ask for different things. It's not the anchor that is helping.

    The regex /^.*(?!system)/ says "does there exist some number of characters which is not immediately followed by 'system'?". And yes, there are many such solutions in strings such as "infosystem". The letter "i" is not followed by system. The letters "in" are not followed by system. The letters "inf" are not followed by system, and so on.

    However, /^(?!.*system)/ says "starting from the beginning of the string, do I fail to match any sequence of characters followed by 'system'?". So, if the inner match fails, the outer match succeeds, and that's exactly what we want. Not that without the anchor, the outer start point could move all the way past the "s" in system, and then the inner match would fail causing the outer match to succeed. So the anchor is still needed.

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

      And my lights turned on ...
      Randal, thank you for the clear explanation.

      --
      Olivier