RegexBuilder
← Back to the tools
👀

Lookahead and Lookbehind in Regex: Zero-Width Assertions

A lookaround is a test that does not consume characters. It looks forward or back and asks "is this true here?" without including the checked text in the match. That makes it perfect for validation rules like "must contain a digit" or "not followed by a dot".

Zero-width: look but do not eat

In \d(?=px), the lookahead (?=px) requires the next two characters to be px but only the digit is consumed by the match. This is how you match a digit "that is followed by px" without including px in the result.

Positive lookahead (?=…)

Requires that what follows matches the pattern inside. foo(?=bar) matches foo only when it is followed by bar. It is the natural way to express "X before Y".

Negative lookahead (?!…)

Requires that what follows does NOT match. foo(?!bar) matches foo only when it is not followed by bar — the classic "X not before Y".

Lookbehind (?<=…) and (?<!…)

The backward twins: (?<=@)\w+ matches a word that follows an @ (like the user part of an email) without eating the @. (?<!\d)\d{4} matches four digits not preceded by a digit.

The password pattern

Lookaheads shine in validation. ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$ says: from the start, there must be a digit somewhere, a lowercase somewhere, an uppercase somewhere, and then the whole thing is at least 8 characters. Three independent checks, one compact pattern — see it tokenized in the RegexBuilder explainer.

Test and explain patterns free