Skip to main content
Regexflux
Lesson 8 of 120 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

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

Matches digits preceded by "$" — the "$" is not part of the match

$100 off
total $42
100 dollars
USD 50

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