Regex Lookahead and Lookbehind Tutorial (Zero-Width Assertions Explained)
Master positive and negative lookaheads (?=), (?!), and lookbehinds (?<=), (?<!). Learn how zero-width assertions match patterns without consuming characters.
Lookarounds are zero-width assertions: they assert whether a pattern exists ahead of or behind the current position without including matched characters in the final match result. They are indispensable for password validation, currency extraction, and boundary matching.
Solve this problem now with our free Regex Tester & Debugger
Try it instantly in your browser — zero tracking, 100% client-side privacy.
Specification & Architecture Reference
| Syntax | Name | Assertion Purpose |
|---|---|---|
| (?=abc) | Positive Lookahead | Matches only if followed immediately by 'abc' |
| (?!abc) | Negative Lookahead | Matches only if NOT followed by 'abc' |
| (?<=abc) | Positive Lookbehind | Matches only if preceded immediately by 'abc' |
| (?<!abc) | Negative Lookbehind | Matches only if NOT preceded by 'abc' |
Understanding Zero-Width Assertions
In standard regex, matching a character advances the internal cursor. When you match `\d+`, those digits are **consumed** and cannot be matched again by subsequent terms.
**Lookaround assertions** (lookahead and lookbehind) test for patterns without consuming characters. The regex engine checks if the condition is satisfied, then returns the cursor to its starting location.
1. Positive Lookahead: `(?=...)` Used to check that a condition is met further down the string without altering the capture:
// Matches 'USD' only if immediately followed by ' 100'
USD(?=\s100)2. Negative Lookahead: `(?!...)` Used to filter out unwanted prefixes or patterns. For example, match the word "Apple" only when not followed by "Pay":
Apple(?!\sPay)3. Positive Lookbehind: `(?<=...)` Extract values preceded by a specific currency symbol without capturing the symbol itself:
// Captures only '49.99' from '$49.99'
(?<=\$)\d+\.\d{2}Real-World Use Case: Multi-Condition Password Validation Lookaheads allow you to check multiple independent rules at the beginning of a string:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
```Test your zero-width assertions with real sample text using Mickytool's **Regex Tester & Debugger** to see exact capture group offsets and matches highlighted instantly.
Solve this problem now with our free Regex Tester & Debugger
Execute this workflow immediately without saving data on remote servers.
Frequently Asked Questions
Is lookbehind supported in all browsers?
Lookbehind was added to ECMAScript in ES2018. It is supported across all modern browsers (Chrome 62+, Safari 16.4+, Firefox 78+, Edge 79+).
Do lookarounds affect regex execution speed?
Excessive nested lookarounds can increase backtracking if not anchored properly. Use specific character classes rather than wildcard .* within lookarounds.