in reply to Why do zero width assertions care about lookahead/behind?

I think a better explanation of why \b can be used as both a "lookahead" and a "lookbehind" assertion, is that not only is it zero-width in terms of the number of places it advances the current pointer as is the case with (?=), (?!), (?<=) & (?<!).

It is also "zero-width" in terms of the number of characters it matches, which the others aren't.

That is to say, \b doesn't match characters, it matches the transition between two characters. And the transition being measured is always a straight comparison between the character before the pointer and the character after, only the sense of the comparison is changes.

Thus, \b is neither a lookahead nor a lookbehind assertion, it's more a "lookhere" or maybe "lookbetween" assertion.

As an interesting exercise to prove that \b is neither a lookahead nor a lookbehind assertion, try creating one of either than can be used as a substitute for \b.

I realise that my explanation will probably not fit anyone elses mental model, but it works for me:)


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

  • Comment on Re: Why do zero width assertions care about lookahead/behind?

Replies are listed 'Best First'.
•Re: Re: Why do zero width assertions care about lookahead/behind?
by merlyn (Sage) on Oct 14, 2003 at 23:01 UTC
    As an interesting exercise to prove that \b is neither a lookahead nor a lookbehind assertion, try creating one of either than can be used as a substitute for \b.
    I did, proving your assertion wrong.

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

      merlyn++. Neat! It's even a lot quicker than I thought it would be.

      $text = do{ local $/; open W, '<dutch.words' or warn $!; <W> }; print length $text; 2603063 use Benchmark qw[ cmpthese ]; cmpthese( 1, { std=> q[ @words1 = $text =~ m[\b(\w+)\b]g; ], merlyn=> q[ @words2 = $text =~ m[ (?: (?<!\w)(?=\w) | (?<=\w)(?!\w) ) (\w+) (?: (?<!\w)(?=\w) | (?<=\w)(?!\w) ) ]xg ] }); (warning: too few iterations for a reliable count) (warning: too few iterations for a reliable count) s/iter merlyn std merlyn 25.9 -- -50% std 13.0 98% -- print scalar @words1, ' : ', scalar @words2; 227248 : 227248
      ...proving your assertion wrong.

      It could be argued that my assertion that "that \b is neither a lookahead nor a lookbehind assertion, try creating one of either" is correct... in that.

      • It isn't either, it's both!
      • And your neat construct is actually two of each:) and I said "...one of either...".

      but that would probably be a fruitless argument, and takes nothing away from your construction. Once again, it's neat :)


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      Hooray!