How do backreferences match text captured earlier in a regex?
Quick answer
A numbered backreference such as \1 means “match the same text that capture group 1 matched earlier.” For example, \b(\w+)\s+\1\b can match go go: group 1 captures go, and \1 matches go again. In Python and JavaScript, numbered groups are counted by their opening parentheses. A backreference in a pattern is different from referring to a capture in replacement text.
The question, the details, the next step.
A practical checklist
Put parentheses around exactly the text you want to capture.
Count capturing groups by the order their opening parentheses appear;
\1refers to the first.Use a backreference in the pattern only when the later text must equal the captured text.
For Python patterns, consider a raw string such as
r"\b(\w+)\s+\1\b".Test against a short input and check the full match separately from the captured group.
Treat replacement references as a separate syntax from pattern backreferences.
A few more useful answers
Does `\1` match any text that looks similar to the capture?
No. It requires the same captured text again, rather than a new arbitrary character or word. For example, if group 1 captured go, the backreference requires go.
What is the difference between the full match and group 1?
The full match is all the text matched by the pattern. In go go, group 1 is the first go, while the full match includes both copies and the separating space.
Can I use a pattern backreference to replace the captured text?
A pattern backreference checks the match; it does not perform a replacement. Replacement text uses its own capture-reference syntax, such as Python’s \g<1> in re.sub().
Sources
References used for this guide.
- [S1] Python Regular Expression HOWTO: numbered backreferences docs.python.org · Checked
- [S2] MDN: JavaScript numbered backreferences developer.mozilla.org · Checked
