Regex in practice
Lookahead
Goal: Check conditions without consuming text using (?=…) and (?!…) · 9 min
A lookahead checks what comes next without including it in the match. It is a zero-width assertion, like an anchor.
(?=…)positive lookahead: what follows must match.(?!…)negative lookahead: what follows must not match.
Examples:
\d+(?= EUR)matches the number in "50 EUR" but not the text " EUR": the match is "50".q(?!u)matches a "q" that is not followed by "u".
Password rules are the classic use. Several lookaheads at the start, all checked from the same position, combine conditions:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$
Read: from the start, "somewhere there is a digit" AND "somewhere a lowercase letter" AND "somewhere a capital letter", and the text has at least 8 characters.
JavaScript also supports lookbehind (?<=…) and (?<!…), which look at the text before the current position.
Worked example: Prices in euro only
- Text: "50 EUR, 30 USD, 20 EUR".
/\d+(?= EUR)/gfinds the numbers followed by " EUR".- Matches: "50" and "20". The text " EUR" is not part of them.
console.log(JSON.stringify("50 EUR, 30 USD, 20 EUR".match(/\d+(?= EUR)/g)));Output:
["50","20"]