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[RegExr] [Visual]- 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[RegExr] [Visual]- 1 match
e_ee_
 - 1 match
u_uu_
 - 1 match
uw_uwuw_
 - 1 match
uw_uwauw_
 - 0 matches
f_f - 0 matches
a_e 
After (?=[aeiou]), the regex engine hasn’t moved and checks for (?=\1) starting after the _.
/(?=.*#).*/g[RegExr] [Visual]- 1 match
abc#defabc#def
 - 1 match
#def#def
 - 1 match
abc#abc#
 - 0 matches
abcdef 
Negative
/_(?![aeiou])/g[RegExr] [Visual]- 0 matches
_a - 0 matches
e_e - 1 match
_f_
 
/^(?!.*#).*$/g[RegExr] [Visual]- 0 matches
abc#def - 0 matches
#def - 0 matches
abc# - 1 match
abcdefabcdef
 
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[RegExr] [Visual]- 1 match
foobazfoo
 - 0 matches
foobarbaz - 0 matches
bazfoobar 
/---(?:(?!---).)*---/g[RegExr] [Visual]- 1 match
---foo------foo---
 - 1 match
---fo-o------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,}$/[RegExr] [Visual]- 0 matches
hunter2 - 0 matches
zsofpghedake - 0 matches
zsofpghedak4e - 1 match
zSoFpghEdaK4EzSoFpghEdaK4E
 - 1 match
zSoFpg!hEd!aK4EzSoFpg!hEd!aK4E
 
Lookarounds can be used verify multiple conditions.
Quoted strings
/(['"])(?:(?!\1).)*\1/g[RegExr] [Visual]- 1 match
foo "bar" baz"bar"
 - 1 match
foo 'bar' baz'bar'
 - 1 match
foo 'bat's' baz'bat'
 - 1 match
foo "bat's" baz"bat's"
 - 1 match
foo 'bat"s' baz'bat"s'
 
Without lookaheads, this is the best we can do:
/(['"])[^'"]*\1/g[RegExr] [Visual]- 1 match
foo "bar" baz"bar"
 - 1 match
foo 'bar' baz'bar'
 - 1 match
foo 'bat's' baz'bat'
 - 0 matches
foo "bat's" baz - 0 matches
foo 'bat"s' baz