Search code examples
regexperlregex-lookarounds

Regex matching multiple negative lookaheads


I'm trying to match a string (using a Perl regex) only if it doesn't start with "abc:" or "defg:", but I can't seem to find out how. I've tried something like

^(?:(?!abc:)|(?!defg:))

Solution

  • Lookahead (?=foo), (?!foo) and lookbehind (?<=foo), (?<!foo) do not consume any characters.

    You can do multiple assertions:

    ^(?!abc:)(?!defg:)
    

    or:

    ^(?!defg:)(?!abc:)
    

    ...and the order does not make a difference.


    You can use De Morgan (as other answers do):

    (NOT A) AND (NOT B) <=> NOT (A OR B) 
    

    ...and shorten the expression to:

    ^(?!abc:|defg:)