Regex matching multiple negative lookaheads

14,879

Solution 1

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.

Solution 2

Try doing this:

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

Solution 3

Use this regex:

^(?!abc:|defg:)\s*\w+

This will avoid line start with "abc:" and "defg:" as you want.

Solution 4

… or we could have dropped the alternation from the original expression:

^(?:(?!abc:)(?!defg:))
Share:
14,879

Related videos on Youtube

tobbo
Author by

tobbo

Updated on September 18, 2022

Comments

  • tobbo
    tobbo over 1 year

    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:))
    
    • ysth
      ysth over 9 years
      that asks for any string that doesn't start abc: or doesn't start defg:, which is any string
  • nhahtdh
    nhahtdh over 9 years
    The preceding \b are redundant, and OP doesn't say anything about whatever that follows.