Numbered Backreferences in Patterns
You'll learn how to use numbered backreferences (\1, \2, etc.) to match repeated text within the same regular expression pattern.
What Are Backreferences?
When you create a capture group with parentheses (), the regex engine remembers what that group matched. A backreference lets you refer back to that captured text within the same pattern to match it again.
Think of it like saying: "Whatever you just matched in the first parentheses group, match that exact same text again right here."
How Numbered Backreferences Work
The syntax is simple:
\1refers to the first capture group\2refers to the second capture group- And so on...
const pattern = /(\w+)\s+\1/;
pattern.test('hello hello'); // true - same word repeated
pattern.test('hello world'); // false - different words
pattern.test('test test'); // true
In the pattern /(\w+)\s+\1/, the \1 means "match whatever the first (\w+) captured."
Matching Repeated Words or Characters
const doubleWord = /\b(\w+)\s+\1\b/;
doubleWord.test('the the'); // true
doubleWord.test('the cat'); // false
const doubleChar = /(.)\1/;
doubleChar.test('hello'); // true - 'll' matches
doubleChar.test('world'); // false - no doubles
Multiple Backreferences
const pattern = /(\w+) and (\w+), \2 and \1/;
pattern.test('cats and dogs, dogs and cats'); // true
Here \2 references the second group, \1 references the first.
Key Takeaway: Numbered backreferences (\1, \2) let you match repeated text within a pattern by referencing what a capture group already matched, perfect for detecting duplicates or mirrored structures.