Regex · <code>\1</code> refers to the first capturing group

Backreferences

A backreference matches the same text captured earlier by a group, such as \1 or \k<name>.

Key facts

Numbered<code>\1</code> refers to the first capturing group
Named<code>\k&lt;name&gt;</code> in JavaScript and PCRE
Python named<code>(?P=name)</code>
MatchesThe exact text captured, not the pattern again
Forward referenceNot allowed in most engines
RE2 / linear enginesBackreferences unsupported
CostCan cause heavy backtracking

Same text, not the same shape

(\w+) \1 matches a repeated word such as “the the”. It does not match two different words of the same shape, because a backreference replays the captured characters. That distinction is exactly what makes it useful for doubled words, matched quotes and repeated delimiters.

Backreferences do not work in every regex engine. RE2, Go's regexp and other linear-time engines omit them because matching them can require unbounded backtracking. A pattern that relies on backreferences locks you into a backtracking engine.

Named references and pitfalls

Named groups make references readable: (?<quote>['"]).*?\k<quote> states which delimiter must repeat. Numbering still works but shifts when groups are added, which is fragile in a pattern maintained over time.

Inside character classes a backreference is not interpreted; and a reference to a group that did not participate in the match generally fails. When debugging a pattern that “should match”, check participation of the referenced group first.

Frequently asked questions

What does \1 do in a regex?

It matches the exact text captured by the first group. It does not re-run the group's pattern.

Can I use backreferences in Go or RE2?

No. Those engines do not support backreferences, which lets them guarantee linear-time matching.

How do I reference a named group?

Use \k<name> in JavaScript and PCRE, or (?P=name) in Python.

New tools, straight to your inbox

One short email when we add tools worth using. No spam, unsubscribe anytime.