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:
(['"]).+?\1matches 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).