Regex Negative Lookahead – Exclude a Following Pattern

Local only

Use negative lookahead to exclude one following context while still matching the base token in other positions.

17 chars · 1 line

8 chars · 1 line

Pattern did not match the inputFlags: g

Regex lookahead behavior

How to use negative lookahead in JavaScript regex

Negative lookahead (?!...) rejects a candidate match when the unwanted following pattern is present. In the sample, foo inside foobar is excluded while foo in fooqux and the standalone foo are still returned. This tool is free to use. No account or payment is required.

Last updated

What you can do here

  • Negative lookahead example
  • Exclusion assertion
  • Match All output
  • JavaScript RegExp semantics
  • Context-sensitive matching
  • Browser-local processing

Steps

  1. Write the base token that should normally match.
  2. Place the disallowed following context inside (?!...).
  3. Run Match All over examples containing both excluded and allowed suffixes.

Negative lookahead rejects context without consuming characters

Like positive lookahead, negative lookahead is zero-width. It checks the upcoming text at the current position and either allows or rejects the candidate match without adding the asserted text to the result.

Negative lookahead example

Match foo except when bar follows immediately.

Pattern and input

foo(?!bar) / g
foobar fooqux foo

Matched positions

foo at index 7
foo at index 14

Common questions

Frequently asked questions

Does (?!bar) consume bar?

No. It only checks whether bar starts at the current position after foo.

Why not just use a negative character class?

A negative character class excludes individual characters, while negative lookahead can reject a multi-character pattern or more complex condition.

Can negative lookahead be combined with captures?

Yes, provided the overall JavaScript regex remains valid and the resulting behavior is tested against representative inputs.

Debugging a specific Regex issue? Browse Regex troubleshooting.