Backreferences: Referring to Previous Captures
You'll learn how to use backreferences to match repeated or mirrored text within a single pattern.
What Are Backreferences?
A backreference lets you refer back to text captured by an earlier group within the same pattern. You write them as \1, \2, \3, etc., where the number corresponds to the capturing group number. This allows you to match patterns where the same content appears multiple times.
Think of it like this: You're looking for duplicate words in a sentence. Instead of writing the word twice in your pattern, you capture it once and say "match that same thing again."
How Backreferences Work
When you use \1 in a pattern, the regex engine looks at what group 1 captured and tries to match that exact text again at the current position. If group 1 captured "cat", then \1 will only match "cat" at that point in the string.
Pattern pattern = Pattern.compile("(\\w+)\\s+\\1");
Matcher matcher = pattern.matcher("hello hello");
if (matcher.matches()) {
System.out.println("Found duplicate: " + matcher.group(1)); // "hello"
}
Here (\\w+) captures a word, \\s+ matches whitespace, and \\1 ensures the next word is identical to the first.
Common Use Cases
- Detecting duplicate words:
(\w+)\s+\1 - Matching HTML tags:
<(\w+)>.*?</\1>(opening and closing tags match) - Finding repeated characters:
(.)\1+(a character followed by itself one or more times) - Palindrome patterns:
(.)(.)\2\1(matches four characters in mirror order)
Key Takeaway: Backreferences (\1, \2, etc.) let you match previously captured text within the same pattern, enabling detection of repeated or mirrored content without knowing the exact value in advance.