C.W.K.
Stream
Lesson 03 of 10 · published

Negative Lookahead — (?!...)

~8 min · lookahead, negative

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Assert that something does NOT follow

(?!...) is the inverse: "at this position, the pattern inside does NOT match." Same zero-width behavior — no characters consumed. The match succeeds only if the lookahead pattern would FAIL.

Common patterns

Match a word UNLESS it's followed by a specific suffix. cat(?!s) matches 'cat' but not 'cats' — the negative lookahead asserts 's' does not come next.

Find tokens that aren't followed by a stop word. Useful for parsing where you want "any word EXCEPT when followed by reserved words."

Avoid false positives in URL detection. http(?!s://) matches 'http' but not 'https://' — useful when you want to upgrade plain HTTP references but skip already-secure ones.

The mental flip

Most beginners struggle with negative lookahead because it requires inverting the question. Instead of "what should match?" you ask "what should the next thing NOT be?" Practice helps; the cleanest patterns often use a positive description in the main match plus a negative lookahead to exclude one specific case.

Code

Negative lookahead patterns·python
import re

# 'cat' but not 'cats'
re.findall(r'\bcat(?!s)\b', 'cats and a cat scatter')
# ['cat']  — only the standalone 'cat'

# Plain 'http' but not 'https://'
re.findall(r'http(?!s://)', 'http://a.com https://b.com httpd')
# ['http', 'http']  — first http and the 'http' in httpd

# Number not followed by 'rd' (so not '3rd')
re.findall(r'\b\d+(?!rd\b)', '1st 2nd 3rd 4th 7 11')
# ['1', '2', '4', '7', '11']  — '3' excluded because 'rd' follows

# Words that aren't followed by 'ing'
re.findall(r'\b\w+(?!ing)\b', 'run running jump jumping read')
# Note: this is tricky because \w+ is greedy — adjust pattern as needed

External links

Exercise

Write a regex that finds the word 'test' UNLESS it's part of 'testing', 'tested', or 'tests'. Test against test the testing tested tests. Only the standalone 'test' should match.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.