Lookaheads and lookbehinds are among the most powerful regex features, yet they remain underused because many developers find them confusing. These zero-width assertions check for a pattern at a position without consuming any characters, letting you match based on context while keeping the match result clean.
The Four Types
Positive Lookahead (?=...)
Succeeds if the pattern matches looking forward. `\d+(?= dollars)` matches digits followed by " dollars" without including the text in the match.
Negative Lookahead (?!...)
Succeeds if the pattern does not match looking forward. `\d+(?!\d|\.)` matches digits not followed by another digit or decimal point.
Positive Lookbehind (?<=...)
Succeeds if the pattern matches looking backward. `(?<=\$)\d+` matches digits preceded by a dollar sign without including it.
Negative Lookbehind (?<!...)
Succeeds if the pattern does not match looking backward. `(?<!\d)\.\d+` matches decimals not preceded by a digit.
Practical Applications
Password Validation
Lookaheads validate multiple criteria simultaneously: `^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$` checks for uppercase, lowercase, digit, and minimum length in one pattern. Each lookahead checks one requirement independently.
Number Formatting
Adding commas to large numbers is a classic lookahead use case. The pattern `\d(?=(\d{3})+$)` identifies positions where commas should be inserted, transforming `1234567` into `1,234,567`.
Engine Limitations
Not all engines support the same features. JavaScript added lookbehinds in ES2018. Most engines require fixed-length lookbehinds. .NET is a notable exception allowing variable-length lookbehinds. Always verify support in your target engine.
Testing Lookarounds
Because lookarounds do not consume characters, their behavior can be counterintuitive. RegExpress provides real-time visual feedback, making it easy to see how lookaheads and lookbehinds affect your pattern as you build it.