Sign in Start free

13Lookahead (?= ) and (?! )

Check what comes next without consuming it.

A lookahead is a test: (?=…) succeeds if the text that follows matches, (?!…) succeeds if it does not. The lookahead itself matches no characters, so the next token starts at the same position.

\d+(?= dollars) matches 100 in 100 dollars but nothing in 100 euros. Lookaheads at the start of a pattern are great for "must contain" rules: ^(?=.*\d)(?=.*[A-Z]).{8,}$ requires a digit, an uppercase letter and at least 8 characters.

Exercises