Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

regex substring negation

by spx2 (Chaplain)
on Jul 02, 2007 at 08:55 UTC ( #624400=perlquestion: print w/ replies, xml ) Need Help??
spx2 has asked for the wisdom of the Perl Monks concerning the following question:

is there any way of making a regex that negates a substring? i know from the documentation only of regexes that negate classes of characters. so for a substring i should o like /^s^u^b^s^t^r^i^n^g/ are there official methods for this ? thank you

Comment on regex substring negation
Re: regex substring negation
by johngg (Abbot) on Jul 02, 2007 at 09:27 UTC
    If you mean that you only want the match to succeed if a string doesn't contain a substring you could use a negative look-ahead.

    my $string = q{the quick black fox}; my $substring = q{brown}; if ( $string =~ m{\A(?!.*\Q$substring\E).*fox} ) { print qq{Found a non-$substring fox\n}; } else { print qq{Match failed, $substring seen\n}; }

    I hope this is of use.

    Cheers,

    JohnGG

    Update: Typo, s/negatine/negative/

Re: regex substring negation
by Limbic~Region (Chancellor) on Jul 02, 2007 at 12:18 UTC
Re: regex substring negation
by Cody Pendant (Prior) on Jul 02, 2007 at 13:40 UTC
    I'm confused. Isn't a regex which negates a substring just a negative regex?

    As in, if you want to test that your string doesn't contain "foo", you just do !~ /foo/?

    Or indeed, use the substring function itself.

    --
    Nobody says perl looks like line-noise any more ...
    kids today don't know what line-noise IS.
    --
Re: regex substring negation
by Zaxo (Archbishop) on Jul 03, 2007 at 03:01 UTC

    The expression (-1 == index $string, "substring") will be true if $string does not contain "substring".

    After Compline,
    Zaxo

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2014-09-02 23:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (33 votes), past polls