C.W.K.
Stream
Lesson 03 of 12 · published

Backreferences — \1, \2

~10 min · backreference, duplicate, engine

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Reuse a captured group inside the same pattern

A backreference says "match the same text that the Nth captured group matched." Syntax: \1 for group 1, \2 for group 2, etc.

Classic example: detect duplicate words. Pattern \b(\w+)\s+\1\b matches "the the", "and and", "hello hello" — any word followed by itself.

How it differs from re-using the pattern

Backreference \1 doesn't repeat the PATTERN; it requires the SAME TEXT that the group matched. Pattern (\w+) \1 against "the cat": group 1 captures 'the', then \1 requires the literal text 'the' to follow — which it doesn't ('cat' is next). So no match.

Versus (\w+) (\w+) which would match "the cat" because \w+ matches any word both times.

Engine support

Backreferences are an NFA-only feature. Python re, JavaScript, PCRE, Java all support them. RE2/Go/ripgrep do NOT support them — that's the price of guaranteed linear time.

Use cases beyond duplicates

  • Matching balanced quotes/brackets: (['"]).+?\1 matches a quoted string with any quote type.
  • Repeated character runs: (.)\1{2,} matches 3+ of the same character.
  • HTML tag pairs: <(\w+)>.+?</\1> matches matching open/close tag (don't actually parse HTML this way).

Code

Backreference patterns·python
import re

# Duplicate word detection
re.findall(r'\b(\w+)\s+\1\b', 'the the cat sat sat by the river')
# ['the', 'sat']

# Triple+ repeated character
re.findall(r'(.)\1{2,}', 'AAAAbbbcccccc')
# ['A', 'b', 'c']

# Matching quote type — single OR double, but consistent
pattern = r'([\'"])([^\'"]+)\1'
re.findall(pattern, '"double" or \'single\' but not "mixed\'')
# [('"', 'double'), ("'", 'single')]  — "mixed\' rejected

# Tag pair (loose)
re.findall(r'<(\w+)>([^<]*)</\1>', '<b>bold</b> <i>italic</b>')
# [('b', 'bold')]  — second pair has mismatched tags

External links

Exercise

Write a regex that finds palindromic 3-letter words (same first and last letter, like 'eye', 'pop', 'mom'). Use a backreference. Test against eye saw pop and mom but not lol.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.