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

If \b, a zero-width assertion, doesn't care whether it's placed before or after the word it's guarding (so to speak), why should (?= ) care that it is for lookahead only? What is it that makes (?<= ) necessary, and (?= ) unable to fill both niches?

You seem to be under the assumption that (?= ) and (?<= ) match the same thing. That isn't true, as the program below shows:

#!/usr/bin/perl use strict; use warnings; no warnings qw /syntax/; $_ = "---abc"; print "Lookahead matches\n" if /(?=abc)\w/; print "Lookbehind matches\n" if /(?<=abc)\w/; __END__ Lookahead matches

See, if (?= ) and (?<= ) are different, no construct could replace them both.

Abigail

Replies are listed 'Best First'.
Re: Re: Why do zero width assertions care about lookahead/behind?
by Roger (Parson) on Oct 09, 2003 at 01:51 UTC
    Hi Abigail, I am a bit confused with the look behind match in your example, I believe that /(?<=abc)\w/ should never match because the look behind does not include the character at the cursor. Does this means that if I want to do a look behind match, I have to know more precisely about the position that I look behind from? I have changed the look behind match in your example to /(?<=abc)\b/, which seems to match "---abc" in the example you have given.

      Both /(?=abc)\b/ and /(?<=abc)\b/ match the string "---abc", but not at the same position, as the program below shows:
      #!/usr/bin/perl use strict; use warnings; $_ = "---abc"; /(?=abc)\b/ and print "Lookahead \$` = '$`'; \$' = '$''\n"; /(?<=abc)\b/ and print "Lookbehind \$` = '$`'; \$' = '$''\n"; __END__ Lookahead $` = '---'; $' = 'abc' Lookbehind $` = '---abc'; $' = ''
      /(?=abc)\b/ matches at a word boundary that is followed by "abc", hence after "---", but before "abc". /(?<=abc)\b/ matches at a word boundary that is preceded by "abc", hence after "abc", and right before the end of the string.

      Abigail