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,