Negative lookahead regex
How negative lookahead (?!...) works in regular expressions: syntax, practical examples, common pitfalls, safe replacements and engine support.
What negative lookahead does
A negative lookahead is a regular expression assertion written as (?!...). At the current position in the text, the engine checks whether the pattern inside the parentheses could match there. If it could, the match fails at that position. If it could not, matching continues. The assertion is zero-width, which means it consumes no characters, so the text it inspects never becomes part of the match.
A negative lookahead never changes your text on its own. It narrows which matches a search finds, and so it narrows which pieces a replace operation touches. Use it when your rule sounds like "match X, but not when Y comes next" or "match lines that do not contain Y".
Syntax
X(?!Y)
Read this as: match X only where Y does not immediately follow. Y can be any pattern. It can be a literal word, a character class, a set of alternatives such as (?!a|b), or .* followed by a word to look across the rest of the line.
Basic example: a word not followed by another
Example (illustrative, based on standard lookahead behavior): the pattern foo(?!bar) applied to a short input.
Pattern: foo(?!bar)
Input: foobar foobaz food
Matches: "foo" in foobaz, "foo" in food
The first foo is rejected because bar follows it. In the other two cases, the matched text is only the three letters foo. The characters that come after foo are not included in the match.
Matching lines that do not contain a word
To match whole lines that lack a word, put the lookahead at the start of the line. Then let it scan the rest of the line with .*:
^(?!.*error).*$
Turn on the multiline flag (m) so that ^ and $ mark the start and end of each line. Without that flag, they refer to the start and end of the whole input. In most engines, the dot does not match line breaks by default. That keeps the lookahead's scan inside the current line.
Input (three lines):
ok: started
error: disk full
ok: finished
Expected matching lines: "ok: started" and "ok: finished"
The check is case-sensitive unless you turn on the case-insensitive flag (i). With the pattern above, a line containing "Error" would still match. The pattern also excludes any line where error appears inside a longer word, such as "errors". To exclude error only as a whole word, add word boundaries: ^(?!.\berror\b).$
Excluding a suffix, such as a file extension
^(?!.*\.bak$).+$
This pattern matches non-empty lines that do not end in .bak. The dot is written as . because an unescaped dot matches any character. For example, take the lines "notes.txt", "notes.txt.bak" and "backup.bakery". The expected matches are "notes.txt" and "backup.bakery", because only the middle line ends with .bak.
Step by step in a regex tester
- 1. Paste sample text that includes lines that should match and lines that should not. Add edge cases too: matches at the end of a line, uppercase variants and empty lines.
- 2. Write the base pattern first, without the lookahead, and confirm that it finds every candidate.
- 3. Add (?!...) at the exact position where the unwanted text would begin.
- 4. Set the flags you need: multiline for per-line anchors, and case-insensitive if capitalization should not matter.
- 5. Check every highlighted match, and confirm that none of the excluded cases is highlighted.
- 6. If you are replacing text, preview the result before applying it, and confirm that only the intended characters change.
Common pitfalls
Backtracking lets a shorter match slip through
When the lookahead fails, a quantifier can give back characters and try again. Suppose you want numbers that are not followed by px. The pattern \d+(?!px) still matches 10 inside 100px. After the engine drops one digit, the next character is 0 rather than px, so the lookahead succeeds.
Pattern: \d+(?!px)
Input: 100px 50em
Matches: "10" (inside 100px), "50"
Pattern: \d+(?!\d|px)
Input: 100px 50em
Matches: "50"
Adding \d to the lookahead stops the match from ending in the middle of a number. Some engines offer another fix through possessive quantifiers or atomic groups, but support for those varies between engines.
Lookahead versus a negated character class
The patterns q[^u] and q(?!u) look alike but behave differently. [^u] consumes one character, so a character must exist after q, and that character becomes part of the match. As a result, q[^u] cannot match a q at the very end of the text. q(?!u) matches the q alone, including at the end of the text.
Input: qatar queen Iraq
q[^u] matches "qa" in qatar; nothing in Iraq (no character after q)
q(?!u) matches "q" in qatar and "q" in Iraq
Placement matters
The lookahead is tested at the exact position where it appears in the pattern. For example, (?!bar)foo has no effect. Wherever foo starts, bar cannot also start, so the pattern behaves exactly like foo. Place the lookahead right after the part it restricts. Alternatively, place it at the start of the pattern and use .* inside it to check the rest of the line.
Replacing text with a negative lookahead
Because the lookahead is zero-width, a replacement rewrites only the text that the main pattern consumed. The text the lookahead inspected stays exactly as it was.
// Illustrative JavaScript; the result shown is expected, not captured from a run
const input = "foobar foobaz";
const output = input.replace(/foo(?!bar)/g, "qux");
// expected: "foobar quxbaz"
Where negative lookahead is supported
Support depends on the regex engine your tool uses. Engines whose documentation lists (?!...) include JavaScript, Python's re module, PCRE (used by PHP, and by grep -P where it is available), Java and .NET. POSIX basic and extended regular expressions do not support it, and those are what grep, sed and awk use by default. RE2, the engine behind Go's regexp package, does not support it either. In a tool without support, the pattern may cause an error, or the tool may treat the characters literally and simply match nothing. Before relying on the pattern, check your tool's documentation or test it there.
Limits of this guide
No tool-specific evidence was provided for this article. For that reason, it does not compare particular regex testers or make claims about performance. The examples follow standard lookahead behavior, and their results are labeled as expected output; they were not run for this guide. Verify them in the engine you actually use.