Regex: negative lookbehind AND negative lookahead

Viewed 1168

I want to match the word gay unless it is part of the word megayacht. I know I can use negative lookahead and negative lookbehind to exclude gayacht or megay from the match, e.g

(?<!me)gay

and

gay(?!acht)

but using

(?<!me)gay(?!acht)

will still exclude megay and gayacht from the match, which is not what I want. I can't find a way to require both simultaneously.

3 Answers

You can use an alternation pattern:

(?<!me)gay|gay(?!acht)

You could exclude matching megayacht and match the word containing gay

\b(?!megayacht\b)\w*gay\w*

regex demo

Use

gay(?!(?<=megay)acht)

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  gay                      'gay'
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
      megay                    'megay'
--------------------------------------------------------------------------------
    )                        end of look-behind
--------------------------------------------------------------------------------
    acht                     'acht'
--------------------------------------------------------------------------------
  )                        end of look-ahead
Related