Learn regular expressions · Lesson 12

Lookahead and lookbehind

A lookaround checks that something is (or isn’t) there, before or after the current position, without taking it into the match. Like an anchor, it matches a position, not text.

  • (?=…) lookahead: what follows matches
  • (?!…) negative lookahead: what follows doesn’t match
  • (?<=…) lookbehind: what comes before matches
  • (?<!…) negative lookbehind: what comes before doesn’t match

Lookahead

\d+(?= kr) is a number followed by “ kr”, without the “ kr” in the match:

/\d+(?= kr)/g2 matches
40 kr, 12 st, 7 kr
Try it in Dotstar →

A negative lookahead leaves out what you don’t want: \b\w+\b(?!\() is a word not followed by a parenthesis, so not a function call:

/\b\w+\b(?!\()/g3 matches
print(total) if done
Try it in Dotstar →

Several conditions at once

Lookaheads at the same position each check the text from there, so they combine as “and”. A toy password rule, to show the technique rather than as a policy: at least eight characters, with a digit and a lowercase letter somewhere in it:

/^(?=.*\d)(?=.*[a-z]).{8,}$/gm1 match
secret12
SECRET12
secret
secretpassword
Try it in Dotstar →

The m flag is there to try four strings at once, one a line; checking a single value, leave it out, or ^ and $ would match at any line of it.

Lookbehind

(?<=\$)\d+ is a number after a dollar sign, without the sign:

/(?<=\$)\d+/g2 matches
$40, 12 USD, $7
Try it in Dotstar →

(?<!-)\b\d+ is a number not preceded by a minus:

/(?<!-)\b\d+/g2 matches
5 -3 12 -8
Try it in Dotstar →

A lookaround doesn’t move

After a lookaround the engine is where it was, so what follows is matched from the same position. That’s why (?=.*\d) can look at the whole line and the .{8,} after it still starts at the beginning. And a lookaround that succeeded isn’t backtracked into: it’s a yes or no.