Lookarounds
Assert context around a match without including that context in the result.· 9 min
Concept
Lookarounds are zero-width assertions — they check what is (or isn't) immediately before or after the current position, without consuming any characters in the match:
- (?=...) — **positive lookahead**: match if the pattern ahead is present
- (?!...) — **negative lookahead**: match if the pattern ahead is NOT present
- (?<=...) — **positive lookbehind**: match if the pattern behind is present
- (?<!...) — **negative lookbehind**: match if the pattern behind is NOT present
Because lookarounds are zero-width, the matched text does not include the lookaround portion. This is useful when you want to match something based on its context without capturing that context.
/\d+(?= dollars)/gPositive lookahead: matches numbers followed by " dollars" — the " dollars" is not part of the match
/\d+(?!px)/gNegative lookahead: matches digits NOT followed by "px" — useful for filtering out CSS values
/(?<=\$)\d+/gPositive lookbehind: matches digits preceded by "$" — the "$" is not part of the match
/(?<!\d)\d{3}(?!\d)/gNegative lookbehind + lookahead: matches exactly 3-digit numbers — not part of longer numbers
Exercise
Write a pattern using a positive lookahead to match numbers that are immediately followed by "px".
Your pattern:
Must match
Must not match
Try These Patterns
See these concepts in action with real-world patterns from the library: