Skip to main content
Regexflux
Lesson 8 of 150 completed

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)/g

Positive lookahead: matches numbers followed by " dollars" — the " dollars" is not part of the match

Pay 50 dollars today
that costs 100 dollars
50 euros
100 USD
/\d+(?!px)/g

Negative lookahead: matches digits NOT followed by "px" — useful for filtering out CSS values

width: 100px and 50em
font: 14px
order 42 items
margin: 0px
/(?<=\$)\d+/g

Positive lookbehind: matches digits preceded by "$" — the "$" is not part of the match

$100 off
total $42
100 dollars
USD 50
/(?<!\d)\d{3}(?!\d)/g

Negative lookbehind + lookahead: matches exactly 3-digit numbers — not part of longer numbers

error 404 not found
code 12345
areas 100 200 3000
no numbers

Exercise

Write a pattern using a positive lookahead to match numbers that are immediately followed by "px".

Your pattern:

Must match

width: 100px
font-size: 14px
padding: 8px
margin: 0px

Must not match

100em
14pt
px100
100 px

Try These Patterns

See these concepts in action with real-world patterns from the library: