Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Groups, Backreferences and Lookaround

Lookbehind

Use positive and negative lookbehind in JavaScript regular expressions to check what comes before a position. Covers variable-length lookbehind, currency and prefix examples, and engine differences.

Lookahead checks what comes after a position. Lookbehind checks what comes before it, again without consuming anything.

Syntax Name Succeeds when...
(?<=...) positive lookbehind the text just before does match
(?<!...) negative lookbehind the text just before does not match

Do not confuse (?<=...) and (?<!...) with a named group (?<name>...): the character after < tells them apart (=, ! or a name).

Positive lookbehind

(?<=\$)\d+ matches digits only when they are directly preceded by a dollar sign, and the dollar sign is not part of the match.

Node.js Preceded by...

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Negative lookbehind

(?<!...) requires the text before the position to not match.

Node.js Not preceded by...

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The escaped-quote example is a very practical use: find the quotes that are not preceded by a backslash. (Strictly, a string like \\" has an escaped backslash followed by a real quote, which this simple check misses; use a tokenizer for that.)

Variable length: a JavaScript strength

In many engines (PCRE, Python, Ruby) the lookbehind pattern must have a fixed length. JavaScript's engine allows any pattern, including *, + and alternations of different lengths.

Node.js Variable-length lookbehind

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second example shows alternatives of different lengths (Mr., Mrs., Dr.) inside one lookbehind. Remember that a lookbehind checks the text immediately before the position: the \s in each alternative matters, because the name starts right after the space.

Variable-length lookbehind is flexible but can be slow on long text, because the engine matches the lookbehind backwards from every candidate position. Keep lookbehinds short and specific, and avoid .* inside them.

How lookbehind matches backwards

The engine evaluates a lookbehind from right to left. For (?<=ab)c at the position before c it reads b, then a going backwards. This is why captures inside a lookbehind can seem to be in reverse order in complex patterns.

Node.js Captures inside lookbehind

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In JavaScript the groups still hold what you expect here, but be careful with backreferences inside a lookbehind, which are evaluated right-to-left and can refer to groups that appear later in the text.

Practical patterns

Lookbehind shines for "extract the value after a label" and for formatting.

Node.js Extract values after labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For key-value pairs, named groups are often clearer: /user=(?<user>\w+)/. Choose lookbehind when you want the match itself to be only the value, for example when feeding replace.

Engine support

Lookbehind is supported in JavaScript (ES2018; Safari since 16.4), PCRE, Python, Java, .NET and Ruby. Rust's regex crate and RE2 do not offer it. If you must support old Safari, avoid it or provide a fallback with a capturing group.

flowchart LR
  A["Lookahead (?=)(?!)"] --> B["looks to the RIGHT of the position"]
  C["Lookbehind (?<=)(?<!)"] --> D["looks to the LEFT of the position"]
  B --> E["consumes nothing"]
  D --> E

All four lookaround forms are zero-width: they only test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does /(?<=\$)\d+/ match in 'cost $50'?

    The $ is only required before the digits; it is not part of the match.
  2. 2. Which pattern finds 'script' not preceded by 'java'?

    (?<!...) is negative lookbehind: it fails if the text before matches.
  3. 3. What is special about JavaScript lookbehind compared to PCRE or Python?

    JavaScript lets lookbehind contain quantifiers and alternatives of different lengths.
  4. 4. Which engines do NOT offer lookbehind?

    Linear-time engines like RE2 leave out lookaround and backreferences.

Summary

  • (?<=...) and (?<!...) check the text before a position without consuming it.
  • JavaScript allows variable-length lookbehind; many other flavors need a fixed length.
  • Keep lookbehinds short; they are evaluated backwards from every candidate.
  • Use them to extract values after labels, to skip prefixed text and to find unescaped characters.

Next: Replacing with Groups and Functions