Usar regex backreferences
Backreferences \1, \2, ... coincidir el mismo texto como un anterior capturing group. Useful para matching repeated palabras, paired delimiters, y palindromes.
- 1
A backreference \1 (or $1 in some flavors) matches the exact text captured by the first group. \2 matches the second, etc. This is useful for: matching repeated words (\b(\w+)\s+\1\b), paired quotes ("([^"]*)"), HTML tags (<(\w+)>.*?</\1>), and symmetric patterns.
- 2 Probador de regex →
Test backreference patterns. Use \b(\w+)\s+\1\b to find repeated words ("the the"). Use <(\w+)[^>]*>.*?</\1> to match HTML tags with matching open/close. The backreference ensures the closing tag matches the opening tag name.
- 3 Reemplazo con regex →
Use backreferences in replacements. Replace (\w+)\s+\1 with $1 to deduplicate consecutive words: "the the cat" → "the cat". The backreference \1 in the pattern matches the repeated word; $1 in the replacement keeps one copy.
Preguntas frecuentes
- Can backreferences match different text than the group?
- No. A backreference matches the exact same text that was captured by the group. If group 1 captured "hello", \1 matches "hello" literally — not the pattern. This is what makes backreferences useful for matching paired delimiters and repeated content.
- Are backreferences efficient?
- Backreferences can make regex matching NP-complete in the worst case (no linear-time algorithm exists). For simple cases (paired delimiters, repeated words), performance is fine. For complex patterns with backreferences on large input, set a timeout to prevent hangs.