Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

regex substring negation

by spx2 (Deacon)
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

Replies are listed 'Best First'.
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.



    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,

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2016-06-27 23:34 GMT
Find Nodes?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...

    Results (348 votes). Check out past polls.