amazotron has asked for the wisdom of the Perl Monks concerning the following question:

How can I match a string which contains "weird" but does not have "odd" somewhere in the string before it? I have tried negative lookbehind as shown below with no success. The example only works if "odd" immediately precedes "weird".
my $str = "odd an very weird receiver"; if ($str =~ /(?<!odd)weird/) { print "hit"; }
Many Thanks!

Replies are listed 'Best First'.
•Re: negative lookbehind heartburn
by merlyn (Sage) on May 17, 2002 at 21:48 UTC
      Yup, that did it. Many thanks, Randall!
Re: negative lookbehind heartburn
by perlplexer (Hermit) on May 17, 2002 at 22:08 UTC
    Do you have to use lookbehinds? Sometimes negating the problem statement simplifies things a little
    unless ($str =~ /odd.*?weird/){ print "hit!\n"; }
    --perlplexer
      Unfortunately this will also match strings that don't contain the substring "weird". Without using lookbehind lookahead, this problem will probably require two tests (one to test for "weird" and one to test for "odd"), since we only want strings containing "weird" but not "odd" before "weird". That was an odd sentence, how weird. :-)
        Yep, you are right. Thanks for pointing that out.

        --perlplexer