Development

Regex Lookahead and Lookbehind Explained with Examples

How lookahead and lookbehind work, with tested JavaScript examples: password rules, prices, thousands separators and splitting camelCase.

The Debuggers · Updated · 9 min read

Lookahead and lookbehind, together called lookarounds, let a regular expression check what comes before or after a position without including it in the match. They are what you need when the rule is "match X, but only if Y is next to it", or when several conditions must all be true at once. All the examples below were tested in JavaScript and you can try each one in our Regex Tester.

The key idea: checking without consuming

A normal pattern consumes characters. After cat matches, the engine has moved past the t, and the cat is part of the result.

A lookaround is a zero-width check. (?=cat) asks "does cat start here?" and, whatever the answer, leaves the engine at the same position. If the answer is yes, matching carries on; if no, this attempt fails. The checked text is never part of the match.

SyntaxNameSucceeds when
X(?=Y)Positive lookaheadX is followed by Y
X(?!Y)Negative lookaheadX is not followed by Y
(?<=Y)XPositive lookbehindX is preceded by Y
(?<!Y)XNegative lookbehindX is not preceded by Y

Positive lookahead: match only when followed by something

Find USD only where an amount follows it:

"USD 100, EUR 50, USD text".match(/USD(?=\s\d)/g);
// ["USD"] (the first one only)

The match is just USD. The space and digit are checked but not returned.

Negative lookahead: exclude what follows

Match Windows everywhere except in "Windows 95":

[..."Windows 98, Windows 95, Windows 10".matchAll(/Windows(?!\s95)/g)].map((m) => m.index);
// [0, 24] (the 98 and the 10)

Negative lookahead at the start of a pattern is also a common way to say "anything except": ^(?!test) matches strings that do not start with test.

Several rules at once: password checks

Lookaheads shine when every one of several conditions must hold, in any order. Each lookahead at the start of the pattern checks one rule against the whole string, then the engine returns to the start for the next:

const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;

strong.test("Passw0rdx"); // true
strong.test("password1"); // false (no capital letter)
  1. ^ anchors at the start.
  2. (?=.*[a-z]) checks there is a lower case letter somewhere.
  3. (?=.*[A-Z]) checks for a capital.
  4. (?=.*\d) checks for a digit.
  5. .{8,}$ finally consumes the whole string and requires at least eight characters.

A note on the rules themselves: the UK's National Cyber Security Centre and the US NIST guidelines both advise that length matters more than composition rules, and NIST recommends against requiring character types at all. If you are designing a password policy, a minimum length plus a check against lists of breached passwords does more good than this regex.

Positive lookbehind: match after something

Get a price without its currency symbol:

"Price: $50".match(/(?<=\$)\d+/)[0];
// "50"

Or read one value from a key=value string:

"user=ada; role=admin; team=web".match(/(?<=role=)[^;]+/)[0];
// "admin"

Negative lookbehind: exclude what comes before

Match foo unless it is part of barfoo:

[..."myfoo, barfoo".matchAll(/(?<!bar)foo/g)].map((m) => m.index);
// [2] (only the foo in "myfoo")

Matching a position, not text

Because lookarounds have no width, a pattern made only of lookarounds matches a position between characters. That is useful for inserting or splitting.

Thousands separators. Insert a comma at every position that is not at a word boundary and is followed by a multiple of three digits:

"1234567".replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// "1,234,567"

Splitting camelCase. Split between a lower case letter and a capital:

"parseJsonResponseBody".split(/(?<=[a-z])(?=[A-Z])/);
// ["parse", "Json", "Response", "Body"]

No characters are lost, because the split happens at a position rather than on a character.

Mistakes to avoid

  • Forgetting the anchor in validation. Without ^, (?=.*\d) can succeed at any position, and the pattern may accept more than you intended.
  • Putting the lookahead in the wrong place. \d+(?=px) matches the number in 12px; (?=px)\d+ can never match, because a position cannot be both the start of px and the start of digits.
  • Expecting lookarounds to capture. Text inside a lookaround is not part of the match. If you need it, put a capturing group inside: (?=(\d+)).
  • Assuming other languages behave the same. JavaScript allows any pattern inside a lookbehind. Python requires a fixed length there and PHP a bounded one, so (?<=\$\d+) works in JavaScript but is an error in both.

Try them yourself

Paste any of these patterns and your own text into the Regex Tester to see exactly what matches. For the bugs that catch out experienced developers, such as the g flag remembering its position, read our common regex mistakes guide.

Frequently Asked Questions

What is the difference between a lookahead and a normal group?

A normal group matches characters and includes them in the result. A lookahead only checks that the characters are there (or not there) and then carries on from the same position, so nothing it checks becomes part of the match.

Does JavaScript support lookbehind?

Yes. Lookbehind has been part of JavaScript since ES2018 and works in every current browser, including Safari since version 16.4, and in Node.js. Only very old browsers lack it.

Can a lookbehind contain a variable-length pattern?

In JavaScript and .NET, yes: (?<=\$\d+) is allowed. Python, PCRE (PHP) and Java require lookbehind to have a fixed or bounded length, so patterns that work in JavaScript can be rejected there.

Are lookarounds slow?

Not on their own. A lookahead such as (?=.*\d) scans the rest of the input, so several of them at the start of a pattern each read the whole string, which is fine for short values such as passwords but worth avoiding on long text.

Want help with this in a real project?

Our team builds web and mobile software, from planning and design to launch and support.