Backreferences

Intermediate · 9 min

A backreference such as \1 or \k<name> repeats text a group already matched. Find doubled words and matching quotes, and see why it outgrows regular languages.

Before thisCapturing groups and numberingNamed capture groups

anthonywritescode · 9 min

Backreferences

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by anthonywritescodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • \1 inside a pattern means the same text that group 1 matched, not the same pattern. (a|b)\1 matches aa and bb, never ab.
  • Use it to find doubled words, \b(\w+)\s+\1\b, and to close a quote with whatever opened it, (['"]).*?\1. In JavaScript the named form is \k<name>, in Python (?P=name).
  • A backreference to a group that did not take part behaves differently by flavour. JavaScript matches the empty string, Python and Perl fail the match.
  • The i flag applies to the backreference too: /(a)\1/i matches aA.
  • Backreferences let a pattern match things plain regular expressions cannot, like any string written twice, and they are why engines built for guaranteed speed leave them out.

The problem: “the same thing again”

A proofreading rule: flag any word that appears twice in a row, like “the the”. Every tool you’ve met so far can say what a word looks like: \w+. None can say “and this must be the same word as the one before”. A pattern like \w+\s+\w+ finds two words, any two. What you need is for the engine to remember which word it matched, and compare.

You already have the memory: it is the capturing group. A backreference is how a later part of the pattern reads it. Writing \1 means “the exact text that group 1 captured”. It does not mean “whatever group 1’s pattern could match”.

Doubled words

const text = 'the the cat sat on on the mat';
text.match(/\b(\w+)\s+\1\b/g)
// [ 'the the', 'on on' ]

The group (\w+) captures the. Then \s+ takes the space, and \1 must match the again. The \b at both ends matters. Without them, the pattern (\w+)\s+\1 on this is it matched is is, because the engine found the tail is of this followed by the whole word is. With \b the same input returned null. Python gives the same answer for the same pattern as a raw string: re.findall(r'\b(\w+)\s+\1\b', text) gave ['the', 'on']. It returns the group, not the whole match, which the non-capturing groups lesson explained.

Quotes that match their opener

Strings can be written with " or '. A closing quote should equal the opening one. The sloppy version lets either quote close either:

const s = `say "it's" and 'bye' and "x'`;
s.match(/["'].*?["']/g)    // [ `"it'`, `" and '`, `' and "` ]
s.match(/(["']).*?\1/g)    // [ `"it's"`, "'bye'" ]

The first pattern stopped at the apostrophe in "it's" and then produced nonsense pairs across the rest of the line. The second captured the opening quote and demanded the same one to close, so "it's" survived whole and 'bye' was found. The dangling "x' has no partner, so it matched nothing. The named form in JavaScript is \k<q> after (?<q>["']), and in Python it is (?P=q). A pair of HTML-style tags works the same way: /<(\w+)>.*?<\/\1>/ accepted <b>x</b> and rejected <b>x</i>. (It also shows why the later lesson on when not to use regex for HTML exists.)

The i flag carries into the backreference: /(a)\1/i.test('aA') was true, and without the flag, false.

Where flavours disagree

What should \1 do if group 1 never matched? I tried (a)?b\1 on the input b:

JavaScript:  [ 'b', undefined ]    (matches; \1 matched the empty string)
Python 3.9:  None
Perl 5.34:   no match

JavaScript treats a reference to a group that didn’t take part as an empty match. The others fail. The same split exists for forward references: /\1(a)/ matched a in JavaScript, while Python 3.9 refused to compile \1(a) with re.error: invalid group reference 1. Don’t write either form on purpose.

Backreferences also appear outside the pattern, in replacements, and the spelling changes. 'Ada Lovelace'.replace(/(\w+) (\w+)/, '$2, $1') returned Lovelace, Ada. Python’s re.sub(r'(\w+) (\w+)', r'\2, \1', ...) gave the same result, and sed -E 's/([A-Za-z]+) ([A-Za-z]+)/\2, \1/' did too. The replacing lesson covers those in full.

In the POSIX tools, \1 works inside a pattern too. On macOS, grep -E '([a-z]+) \1' printed the the cat for my two-line test, and basic-mode grep '\([a-z][a-z]*\) \1' agreed. A caution when using * for the group: \([a-z]*\) \1 also matched no repeat here, because the group may be empty and \1 then matches nothing.

What it costs: matching what “regular” cannot

Here is a pattern with a backreference that looks harmless: /^(\w+)\1$/ accepts any word written twice.

abab true    abcabc true    abba false    aa true    a false

Another, /^(aa+)\1+$/, tests whether a number written in unary is composite. I ran it on strings of a of lengths 2 to 30:

4 6 8 9 10 12 14 15 16 18 20 21 22 24 25 26 27 28 30

Those are the composite numbers, and the primes (2, 3, 5, 7, 11, …) fall out. That is a surprising amount of power in one line. The textbook result, which I did not prove or run, is that “any string written twice” is not a regular language, so a pattern without backreferences can’t describe it exactly. My understanding, which I didn’t check here, is that engines built to promise linear-time matching, such as RE2, leave backreferences out for that reason. The later lessons on how engines work return to this.

About the video

The embedded video is anthonywritescode’s “regex backreferences (intermediate) anthony explains #450”, published 13 July 2022 and 9 minutes 29 seconds long. Its chapters are Intro, Lesson and Summary. The description says it covers backreferences in three contexts: in the pattern, after matching, and while replacing. It uses Python. I couldn’t read a transcript, so I can’t say how it handles the optional-group case, and it isn’t about the non-regular side of the topic. The JavaScript spellings and the unary-prime example above are my own runs. English per its title and description. The Coding Train’s four-minute JavaScript video on the same topic is the shorter alternative.

What I did not run

GNU grep, newer Python versions, and the proof that doubled strings are not regular.

Next

Backreferences repeat a captured value. Next you’ll look at conditions on the surrounding text that capture nothing at all, starting with lookahead.

Check yourself

  1. 01Why does /(a|b)\1/ match aa and bb but not ab?

    The backreference repeats the text the group actually matched. If the group matched a, \1 must match a again. It is a copy of the captured text, not a re-run of the group's pattern.

  2. 02Why is /(['"]).*?['"]/ a worse quote matcher than /(['"]).*?\1/?

    The first lets either quote close either quote, so on "it's" it stops at the apostrophe and returns "it'. The second requires the closing character to equal the opening one, so it returns the whole "it's".

  3. 03What does /(a)?b\1/ do on the input b in JavaScript, and in Python?

    JavaScript matches it, because \1 refers to a group that never took part and matches the empty string. Python and Perl report no match. Avoid backreferences to optional groups in portable code.

  4. 04How can /^(aa+)\1+$/ identify non-prime lengths of a string of a characters?

    It succeeds when the string splits into two or more equal chunks of at least two a's, which is exactly when the length has a factor other than 1 and itself. So a string of 7 a's fails and a string of 9 passes.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark