A practical guide to lookahead and lookbehind assertions — the most powerful regex features with real examples.
Lookaheads and lookbehinds are zero-width assertions — they check whether a pattern exists ahead/behind the current position without consuming characters.
(?=...) - Positive lookahead
(?!...) - Negative lookahead
(?<=...) - Positive lookbehind
(?<!...) - Negative lookbehind
Match X only if followed by Y:
// Match digits followed by 'px'
"16px 2em 24px".match(/\d+(?=px)/g); // ["16", "24"]
Match X only if NOT followed by Y:
// Match .js files but not .json
/\.js(?!on)/.test("app.js"); // true
/\.js(?!on)/.test("data.json"); // false
Match X only if preceded by Y (ES2018+):
// Match numbers preceded by "$"
"$100 EUR200 $300".match(/(?<=\$)\d+/g); // ["100", "300"]
Match X only if NOT preceded by Y:
// Match 'ing' not preceded by 'think'
/(?<!think)ing/.test("singing"); // true
/(?<!think)ing/.test("thinking"); // false
Password validation with lookaheads:
// At least 8 chars, one uppercase, one digit
/^(?=.*[A-Z])(?=.*\d).{8,}$/.test("Password1"); // true
Extract prices:
const prices = "$9.99 and EUR14.50";
prices.match(/(?<=[$])\d+\.\d{2}/g); // ["9.99"]
Test all lookahead/lookbehind patterns in the Regex Tester.