Script Valley
Regex: Actually Useful Patterns
Lookaheads and LookbehindsLesson 3.2

Negative lookahead in regex to exclude patterns

negative lookahead syntax, exclusion patterns, matching words not followed by something, practical filtering examples

Negative Lookahead: Match When Something Is Absent

Negative lookahead

Syntax: (?!pattern). Succeeds when the pattern does NOT follow the current position.

// Match 'cat' not followed by 's' (no plural)
/cat(?!s)/.test('cat')   // true
/cat(?!s)/.test('cats')  // false

// Whole-number exclusion
'10px 20em'.match(/\b\d+(?!px)\b/g)
// => ['20']

Negative lookaheads are also useful for log filtering: match lines that contain a keyword but are not followed by a known false-positive phrase.

Up next

Lookbehind assertions in regex positive and negative

Sign in to track progress

Negative lookahead in regex to exclude patterns โ€” Lookaheads and Lookbehinds โ€” Regex: Actually Useful Patterns โ€” Script Valley โ€” Script Valley