A negative lookahead assertion is the regex skeptic at the gate: proceed only when a specified pattern cannot be found from the current position. Its usual form is `(?!...)`. That small question mark and exclamation point can express “match this word, but only if the same whole word does not occur later” or “accept this group, but not if a forbidden repetition follows.” section 5.6 section 5.5
No duplicate words lurking ahead
Suppose a match should retain words only when each current word is never repeated later in the string. `((\w+\b)(?!.*\2\b)\W*)+` captures a word, then asks the negative lookahead to search the remaining text for that same captured word. The word boundary after `\2` matters: `cat` need not reject `catalog`. Group numbering matters too; here the outer parentheses occupy group 1, so the word is `\2`. section 5.5
This is powerful, not magical. A lookahead can prohibit a later space-delimited repetition of a captured `@@+` group while another lookahead requires the next group to be longer. But a regex has only finitely many capture groups, so it can exclude multiples of only a fixed finite collection of primes—not recognize every initial sequence of primes. If a pattern appears to solve an unbounded sieve, pause before admiring it. section 5.20 section 5.17
Treat plausible-looking assertions as hypotheses to test:
- Check the polarity. `@(?!.@.@)` is an `@` match followed by a negative lookahead, not a positive lookahead. section 5.15
- Check the scope. A bare negative lookahead may explain a local condition correctly while the whole regex still fails to express the intended sequence rule. section 5.18
- Check counterexamples. A suggested duplicate-word pattern captured the basic idea but matched only the first word or nothing until grouping and repetition were repaired. section 5.6
((\w+\b)(?!.*\2\b)\W*)+
Inspect the duplicate-word pattern as a compact specimen: the assertion searches forward with `.*`, rejects the captured word through `\2`, and uses `\b` to avoid rejecting longer words sharing its prefix. section 5.5
