Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Groups, Backreferences and Lookaround

Lookahead

Use positive and negative lookahead in regular expressions to check what follows without consuming it. Includes password rules, number formatting, excluding words and an atomic-group trick.

Lookaround assertions check whether some pattern matches next to the current position, without consuming any text. They are zero-width, like ^ and \b: they test a condition and leave the match position where it was. There are four kinds. This lesson covers the two that look ahead; the next one covers looking behind.

Syntax Name Succeeds when...
(?=...) positive lookahead the pattern does match next
(?!...) negative lookahead the pattern does not match next

Positive lookahead: (?=...)

foo(?=bar) matches foo only if it is followed by bar, but bar is not part of the match.

Node.js Followed 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 lookahead: (?!...)

foo(?!bar) matches foo only if it is not followed by bar.

Node.js Not followed 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 first pattern puts the lookahead right at the start: ^(?!.*\.test\.) means "at the start, it must not be true that somewhere .test. follows". That is the standard way to say "the text must not contain X".

Several conditions at once

Because lookaheads consume nothing, you can stack several at the same position. Each one checks the whole rest of the text independently, which makes them perfect for rules like passwords.

Node.js Password rules

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.

flowchart LR
  S["start ^"] --> A["(?=.*[a-z])<br/>has lowercase"]
  A --> B["(?=.*[A-Z])<br/>has uppercase"]
  B --> C["(?=.*\\d)<br/>has digit"]
  C --> D["(?=.*[^\\w\\s])<br/>has symbol"]
  D --> E[".{8,}$<br/>consume 8+ chars"]

All four checks happen at position 0. Only the last part consumes characters.

Rules like these are a quick filter for a form. Modern guidance (NIST) prefers long passphrases and breach checks over forced complexity, so treat complexity patterns as a UX hint, not as security.

Formatting numbers with lookahead

A lookahead can find positions instead of text. The classic example inserts thousands separators: at every position that is followed by groups of exactly three digits up to the end of the number.

Node.js Thousands separators

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.

Reading \B(?=(\d{3})+(?!\d)): at a position that is not a word boundary, require that the rest of the digits consists of full groups of three ((\d{3})+) with no extra digit after them ((?!\d)). Replace that empty position with a comma. In real code use toLocaleString or Intl.NumberFormat; the pattern is a fine exercise in thinking with positions.

Lookahead inside a quantifier: whole-token guards

Negative lookahead can protect a repeated token, so it does not run into a forbidden sequence. This is how you match "text up to, but not including, a marker".

Node.js Tempered dot

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.

(?:(?!end)[\s\S])* is called a tempered greedy token: at each step it checks "is this the beginning of end?" and only consumes the character if not. It is more explicit than .*? and lets you forbid several words at once, e.g. (?!end|stop).

Emulating an atomic group

JavaScript lacks atomic groups (?>...) and possessive quantifiers. A lookahead with a capturing group and a backreference mimics them: once the lookahead matched, the engine never goes back into it.

Node.js Atomic group by lookahead

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.

This trick matters again in the performance chapter, where preventing backtracking can stop pathological slowdowns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does /\d+(?= USD)/ match in '10 USD'?

    The lookahead requires " USD" after the digits but does not include it in the match.
  2. 2. Which pattern says 'the text must not contain foo'?

    At the start, assert that foo does not appear anywhere later.
  3. 3. Why can several lookaheads at the same position work together?

    Lookahead is zero-width. The position does not move, so each assertion tests the same remaining text.
  4. 4. What does (?!\d) assert?

    Negative lookahead succeeds when its pattern does not match at the current position, including at the end of the text.

Summary

  • (?=...) and (?!...) assert what follows without consuming it.
  • Stack lookaheads at the start (^(?=...)(?=...)) to combine independent conditions.
  • A lookahead can match a position, which enables tricks like thousands separators and tempered tokens.
  • (?=(x))\1 emulates an atomic group in JavaScript.

Next: Lookbehind