Regex Lookahead and Lookbehind Patterns Explained
Master regex lookahead and lookbehind assertions with practical examples for validation, parsing, and text processing.
Lookahead and lookbehind assertions are zero-width patterns that match a position in a string without consuming characters. They are essential tools for complex validation and text processing.
Understanding Zero-Width Assertions
Regular assertions like ^ (start) and $ (end) match positions, not characters. Lookahead and lookbehind work the same way.
(?=...) Positive lookahead — what follows must match
(?!...) Negative lookahead — what follows must NOT match
(?<=...) Positive lookbehind — what precedes must match
(?
Practical Examples
Password Validation
Enforce complex password rules with a single regex using multiple lookaheads:
// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special char
const strongPassword = /^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[@$!%?&])[A-Za-z\d@$!%?&]{8,}$/;
strongPassword.test('Abc1@def'); // true
strongPassword.test('abcdefgh'); // false
Extracting Prices Without Currency Symbols
const prices = 'Items: $29.99, $149.00, $5.50';
const matches = prices.match(/(?<=\$)\d+\.\d{2}/g);
// ["29.99", "149.00", "5.50"]
Splitting camelCase to Words
const camelCase = 'backgroundColor';
const words = camelCase.split(/(?=[A-Z])/);
// ["background", "Color"]
Negative Lookahead for Exclusions
// Match "foo" only when NOT followed by "bar"
const regex = /foo(?!bar)/g;
'foobar foobaz foo'.match(regex);
// ["foo", "foo"] — matches foobaz and standalone foo
Performance Considerations
Avoid nesting quantifiers inside lookaheads to prevent catastrophic backtracking.
Use our Regex Tester tool to experiment with lookahead and lookbehind patterns interactively.