Regex matching multiple negative lookahead

tobbo picture tobbo · Nov 28, 2014 · Viewed 10.3k times · Source

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:))

Answer

Stephan Stamm picture Stephan Stamm · Nov 14, 2017

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.