Skip to content
Regex

Backreferences

Reuse a previously captured group.

By EZ4Code Team
backreferencecapture

Code

(\w)\1         repeated char (aa, bb)
(\w+)\s\1      repeated word
<(\w+)>.*?</\1>  matching HTML tag pair
([a-c])\1{2}   char repeated 3 times total
(?P<q>['"]).*?(?P=q)  quoted string (Python)
\1 \2 \3       backrefs to groups 1, 2, 3

Explanation

A backreference (\1, \2, ...) matches the exact text captured by an earlier group, enabling patterns like doubled words or matched quote pairs. Named groups can be referenced as (?P=name) in Python or \k<name> in .NET and JavaScript. Backreferences disable some optimizations, so engines cannot always backtrack freely.

More Regex Snippets