Lookahead and Lookbehind
Lookahead and lookbehind are zero-width assertions β they check if a pattern matches without consuming characters.
Lookahead (?=)
Matches if the pattern ahead matches, but doesn't consume it.
foo(?=bar) matches "foo" only if followed by "bar".
Negative Lookahead (?!)
Matches if the pattern ahead does NOT match.
foo(?!bar) matches "foo" only if NOT followed by "bar".
Lookbehind (?<=)
Matches if the pattern behind matches.
(?<=\$)\d+ matches numbers preceded by $.
Negative Lookbehind (?
Matches if the pattern behind does NOT match.
(? matches numbers NOT preceded by $.
Practical Examples
Extract prices without the $ sign:
(?<=\$)\d+\.\d{2}
Find words not followed by punctuation:
\b\w+(?![.,!?])
Validate password has uppercase:
(?=.*[A-Z])
Test these in our Regex Tester to see them in action!