Regular Expressions For Regular Folk

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 — (?!…)
  • Lookbehind
    • Positive — (?<=…)
    • Negative — (?<!…)

Lookahead

Positive

/_(?=[aeiou])/g
  • 1 match_a
  • 1 matche_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 matche_e
  • 1 matchu_u
  • 1 matchuw_uw
  • 1 matchuw_uwa
  • 0 matchesf_f
  • 0 matchesa_e

After (?=[aeiou]), the regex engine hasn’t moved and checks for (?=\1) starting after the _.

/(?=.*#).*/g
  • 1 matchabc#def
  • 1 match#def
  • 1 matchabc#
  • 0 matchesabcdef

Negative

/_(?![aeiou])/g
  • 0 matches_a
  • 0 matchese_e
  • 1 match_f
/^(?!.*#).*$/g
  • 0 matchesabc#def
  • 0 matches#def
  • 0 matchesabc#
  • 1 matchabcdef

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 matchfoobaz
  • 0 matchesfoobarbaz
  • 0 matchesbazfoobar
/---(?:(?!---).)*---/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 matcheshunter2
  • 0 matcheszsofpghedake
  • 0 matcheszsofpghedak4e
  • 1 matchzSoFpghEdaK4E
  • 1 matchzSoFpg!hEd!aK4E

Lookarounds can be used verify multiple conditions.

Quoted strings

/(['"])(?:(?!\1).)*\1/g
  • 1 matchfoo "bar" baz
  • 1 matchfoo 'bar' baz
  • 1 matchfoo 'bat's' baz
  • 1 matchfoo "bat's" baz
  • 1 matchfoo 'bat"s' baz

Without lookaheads, this is the best we can do:

/(['"])[^'"]*\1/g
  • 1 matchfoo "bar" baz
  • 1 matchfoo 'bar' baz
  • 1 matchfoo 'bat's' baz
  • 0 matchesfoo "bat's" baz
  • 0 matchesfoo 'bat"s' baz