Level 3: Advanced · Lesson 22 of 30
Backreferences
A backreference like \1 matches the exact text an earlier group captured. Use it to find doubled words, matching quotes and paired tags.
A capture group remembers what it matched. A backreference lets the pattern itself use that memory later in the same match. Written \1 for group 1, \2 for group 2 and so on, it matches exactly the same characters the group captured, not just the same kind of characters.
The classic example is finding accidentally doubled words. The pattern \b(\w+) \1\b captures a word, expects a space, and then requires the same word again. In This is is a test test case, it matches is is and test test. A pattern like \w+ \w+ cannot do this, because it would accept any two words.
Backreferences are also the way to pair delimiters. To match a string wrapped in either single or double quotes, write (["'])\w*\1. The group captures whichever quote opened the string, and \1 insists that the same quote closes it. A mismatched pair such as a double quote followed later by a single quote is rejected.
The same idea pairs simple tags: <(\w+)>.*?</\1> matches <b>bold</b> but not <b>bold</i>. This is fine for quick searches in small snippets, but remember that regex is not a full HTML parser. Nested tags of the same name will confuse it.
Named groups have named backreferences. In JavaScript, (?<q>["'])\w*\k<q> does the same job as the numbered version and reads more clearly. Python writes the named form as (?P=q).
Support matters here. JavaScript, Python, PHP, Java, C# and Ruby all support backreferences. Go and Rust do not, because a backreference makes matching impossible to guarantee in linear time. If you need portable code, capture both parts and compare them in your program.
Backreferences can also slow matching down, because the engine may retry many different captures to find one that repeats. Keep the captured part specific, such as \w+ or a small character class, rather than a broad .*.
Live tester
2 matches (JavaScript engine)
This is is a test test case.
Examples
Numbers
/(\d)\1/PINs 1123, 4556 and 789
Matches: “11”, “55”
A digit followed by the same digit matches, giving `11` and `55`.
Text
/(["']).*?\1/He said "hi" and 'bye' today.
Matches: “"hi"”, “'bye'”
Each quoted string must close with the same quote character that opened it.
Codes
/<(\w+)>.*?</\1>/<b>bold</b> and <i>slanted</i>
Matches: “<b>bold</b>”, “<i>slanted</i>”
The closing tag must repeat the name captured in the opening tag.
Practice tasks
Your regex runs over the text with the global flag. It passes when it finds every required match and nothing that should be left out.
Task 1: Match doubled words, such as `the the`.
the the cat sat sat down
Task 2: Match any letter that appears twice in a row.
book feel cat dog
Task 3: Match quoted words whose opening and closing quotes are the same character.
say "hi' or "yes" or 'no'