Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Groups, Backreferences and Lookaround

Backreferences

Match the same text twice with regex backreferences. Learn \1 and \k<name>, find repeated words and matching quotes, understand forward and unset references, and see what regular expressions cannot count.

A capturing group remembers text. A backreference lets the pattern use that remembered text again, later in the same pattern. So (\w+) \1 does not mean "a word, a space, any word": it means "a word, a space, and the same word again". This is something no plain character class can do.

\1, \2 and \k

\1 refers to group 1, \2 to group 2, and so on. For named groups, write \k<name>.

Node.js Repeated words

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.

Look at how the engine works for (\w+)\s+\1: group 1 captures a word, then \s+ matches the whitespace, then \1 must match exactly the same text (respecting the i flag).

Matching quotes

A classic use: a string that opens and closes with the same quote character.

Node.js Same quote on both sides

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 mixed quote "mixed' is not matched, because the closing quote must equal the opening one.

Palindromes and repeated patterns

Backreferences can detect structure that character classes cannot.

Node.js Doubles, palindromes and repeats

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.

Matching tags like this works for flat, small examples. For nested or arbitrary HTML, use an HTML parser instead: regexes cannot count nesting depth.

Backreferences in replacement strings

Inside the pattern you use \1. In the replacement string of replace you use $1.

Node.js \1 versus $1

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.

Do not mix them up: \1 in a replacement string is the character with code 1, and $1 in a pattern is the end anchor followed by a 1. Pattern: \1. Replacement: $1.

Special cases

Backreferences have some rules you should know:

  • A reference to a group that has not captured yet (a forward reference) or did not participate matches the empty string in JavaScript. In some other flavors it fails the match instead.
  • \10 and above are references only if that many groups exist; otherwise the digits may be read as an octal escape (in non-Unicode mode). Prefer named references to avoid this.
  • With the u flag, invalid references are syntax errors, which is good.
Node.js References to unset groups

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 result surprises many people coming from Python or PCRE, where (a)?b\1c would fail on bc. Do not rely on this JavaScript-specific behavior.

What backreferences cannot do

Backreferences make a regex stronger than the theory of "regular" languages, but they still do not count. You cannot match "n opening brackets followed by n closing brackets" for any n. Some engines add recursion (PCRE (?R)) for that; JavaScript does not. When you need balanced structures, write a small parser.

Backreferences also cost speed: they force the engine to backtrack and they rule out the guaranteed-linear engines such as RE2.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does /(\w+) \1/ match?

    \1 repeats the exact text captured by group 1.
  2. 2. How do you write a named backreference to a group called q?

    JavaScript uses \k<name> inside the pattern. (?P=name) is the Python syntax.
  3. 3. Which is correct in a replace replacement string to insert group 1?

    Replacement strings use $1, $2 and $<name>. Backslash references belong inside the pattern.
  4. 4. What can a plain regex backreference NOT check?

    Counting arbitrary nesting needs recursion or a parser.

Summary

  • \1, \2 and \k<name> match the same text a group captured earlier.
  • Use them for repeated words, matching quotes, doubled characters and matching tags in simple cases.
  • In replacements use $1 and $<name>; in patterns use \1 and \k<name>.
  • References to unset groups match empty in JavaScript; backreferences cannot count nesting.

Next: Lookahead