Lookaround
Note
This section is a Work In Progress.
Lookarounds can be used to verify conditions, without matching any text.
You’re only looking, not moving.
- Lookahead
- Positive —
(?=…)
- Negative —
(?!…)
- Positive —
- Lookbehind
- Positive —
(?<=…)
- Negative —
(?<!…)
- Positive —
Lookahead
Positive
/_(?=[aeiou])/g
- 1 match
_a
- 1 match
e_e
- 0 matches
_f
Note how the character following the _
isn’t matched. Yet, its nature is confirmed by the positive lookahead.
/(.+)_(?=[aeiou])(?=\1)/g
- 1 match
e_e
- 1 match
u_u
- 1 match
uw_uw
- 1 match
uw_uwa
- 0 matches
f_f
- 0 matches
a_e
After (?=[aeiou])
, the regex engine hasn’t moved and checks for (?=\1)
starting after the _
.
/(?=.*#).*/g
- 1 match
abc#def
- 1 match
#def
- 1 match
abc#
- 0 matches
abcdef
Negative
/_(?![aeiou])/g
- 0 matches
_a
- 0 matches
e_e
- 1 match
_f
/^(?!.*#).*$/g
- 0 matches
abc#def
- 0 matches
#def
- 0 matches
abc#
- 1 match
abcdef
Without the anchors, this will match the part without the #
in each test case.
Negative lookaheads are commonly used to prevent particular phrases from matching.
/foo(?!bar)/g
- 1 match
foobaz
- 0 matches
foobarbaz
- 0 matches
bazfoobar
/---(?:(?!---).)*---/g
- 1 match
---foo---
- 1 match
---fo-o---
- 1 match
--------
Lookbehind
Limited Support
JavaScript, prior to ES2018, did not support this flag.
Positive
Negative
Examples
Password validation
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/
- 0 matches
hunter2
- 0 matches
zsofpghedake
- 0 matches
zsofpghedak4e
- 1 match
zSoFpghEdaK4E
- 1 match
zSoFpg!hEd!aK4E
Lookarounds can be used verify multiple conditions.
Quoted strings
/(['"])(?:(?!\1).)*\1/g
- 1 match
foo "bar" baz
- 1 match
foo 'bar' baz
- 1 match
foo 'bat's' baz
- 1 match
foo "bat's" baz
- 1 match
foo 'bat"s' baz
Without lookaheads, this is the best we can do:
/(['"])[^'"]*\1/g
- 1 match
foo "bar" baz
- 1 match
foo 'bar' baz
- 1 match
foo 'bat's' baz
- 0 matches
foo "bat's" baz
- 0 matches
foo 'bat"s' baz