August 2, 2026
Regex Lookahead and Lookbehind, Explained With Real Examples
Lookahead and lookbehind (together called "lookaround") let a regex check what comes before or after a position in the text without including that part in the actual match — the engine checks the condition, then doesn't move. That's the one idea behind all four variants: positive, negative, ahead, and behind.

Positive lookahead: (?=...)
q(?=u) matches a q, but only when it's followed by a u — and the u itself isn't part of the match. A practical example: \d+(?=px) matches the number in "20px" without capturing the unit, useful when you want the value but not the label attached to it.
Negative lookahead: (?!...)
X(?!Y) means "match X, but only if it's not followed by Y." A common use: matching a word that isn't immediately followed by a specific suffix, like flagging a filename that isn't already suffixed with .test before appending it yourself.
Positive lookbehind: (?<=...)
(?<=\$)\d+(?:\.\d{2})? matches the 19.99 inside $19.99, leaving the dollar sign itself out of the match entirely — the lookbehind confirms a $ precedes the number without consuming it. This is the pattern behind extracting a price or an ID that always follows a fixed label.
Negative lookbehind: (?<!...)
(?<!a)b matches a "b" that isn't preceded by an "a" — it matches the b in "rob" (preceded by o) but skips the b in "cab" (preceded by a). Negative lookbehind is the tool for "match this, but only when NOT immediately after a specific thing."
Why this matters in practice
Lookaround turns validation you'd otherwise need multiple passes or a much bigger pattern for into a single expression — currency parsing, filtering matches by context, and pulling a value out from between fixed labels all lean on it. The one tradeoff: lookbehind support varies more across regex engines and older JavaScript versions than lookahead does, so test the exact pattern in the environment you'll actually run it in.
Want to try this yourself?
Open Regex Tester →