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)/gMatches numbers followed by " dollars" — the " dollars" is not part of the match
/(?<=\$)\d+/gMatches digits preceded by "$" — the "$" is not part of the match
Exercise
Write a pattern using a positive lookahead to match numbers that are immediately followed by "px".
Your pattern: