Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

regex negation without !~

by Anonymous Monk
on May 24, 2007 at 19:14 UTC ( [id://617317]=perlquestion: print w/replies, xml ) Need Help??

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
    Would
    /^(?!FOO)/
    do what you want? From the perlre description, it looks like a negative lookahead is exactly what you're looking for (pun somewhat intended...)

    Mike

      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
    Regards,
    Xicheng
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://617317]
Approved by Old_Gray_Bear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2024-04-23 08:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found