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

Hi, I'd like to use a regex to filter out everything except a fixed string, say "accept everything except 'FOO'". I can easily do this with $str !~ /^FOO$/. But my problem is that I can't use !~, I have to use =~ because I'm passing the pattern to some other code. How do I do that?, I tried $str =~ /^^FOO$/ or /^^F^O^O$/, they certain don't do the right thing. Thanks

Replies are listed 'Best First'.
Re: regex negation without !~
by imp (Priest) on May 24, 2007 at 19:23 UTC
Re: regex negation without !~
by RMGir (Prior) on May 24, 2007 at 19:59 UTC
    do what you want? From the perlre description, it looks like a negative lookahead is exactly what you're looking for (pun somewhat intended...)


      Just to be clear, that doesn't work if the original expression doesn't start with ^.

      >perl -le"print 'abc' !~ /b/ ?1:0" 0 >perl -le"print 'abc' =~ /^(?!b)/ ?1:0" 1 >perl -le"print 'abc' =~ /(?!b)/ ?1:0" 1

      That may not be an issue in this case.

Re: regex negation without !~
by xicheng (Sexton) on May 24, 2007 at 22:34 UTC
    check this out:
    perl -wle ' my @test = qw(FOO FOOBAR FOO AFOO FOO BARFOO FOOFOO FOO1); print "match: $_" for grep { /^(?!FOO$)/ } @test; ' match: FOOBAR match: AFOO match: BARFOO match: FOOFOO match: FOO1
Re: regex negation without !~
by cengineer (Pilgrim) on May 24, 2007 at 19:21 UTC
    if (!($str =~ /^FOO$/)) { //do something for no match }
      This approach won't work, as he is passing the regex to another module. The regex itself has to evaluate as false.