Duplicate Named Group Names
You'll learn how Java handles regular expressions when the same named group appears more than once in a pattern, and what happens when you try to access those groups.
The Core Idea
In most regex engines, named groups must be unique—you can't use the same name twice. However, Java allows duplicate named group names under certain conditions (introduced in Java 7 and refined later). When duplicates exist, accessing that group name retrieves the last matched occurrence of any group with that name.
Think of it like having multiple people named "Alex" in a room. When you call out "Alex!", only the Alex who most recently responded is the one you'll interact with.
How It Works
Java permits duplicate group names primarily when the groups are in different alternatives of a pattern (separated by |). When you call group("name"), you get the text captured by whichever named group actually participated in the match:
Pattern pattern = Pattern.compile("(?<value>\\d+)|(?<value>[a-z]+)");
Matcher m1 = pattern.matcher("123");
if (m1.find()) {
System.out.println(m1.group("value")); // "123" (first group matched)
}
Matcher m2 = pattern.matcher("abc");
if (m2.find()) {
System.out.println(m2.group("value")); // "abc" (second group matched)
}
Only one of the value groups participates in each match because they're alternatives. The matched group determines what group("value") returns.
Important Limitations
Java doesn't allow duplicate names in all contexts—only when they're mutually exclusive (typically in alternations). Attempting duplicates in sequential groups may cause compilation errors depending on your Java version.
Key Takeaway:
Java allows duplicate named group names in mutually exclusive alternatives; calling group("name") returns the text from whichever group with that name actually participated in the match.