Accessing Named Groups with group(String)
What you'll learn: How to retrieve captured text using descriptive group names instead of remembering numeric positions.
The Core Idea
Once you've defined named capturing groups in your pattern using (?<name>...), you can extract the matched text by calling Matcher.group(String name) instead of group(int). This makes your code self-documenting and less brittle—when you add or rearrange groups in your regex, you don't need to renumber every extraction call.
Think of it like using a dictionary with labeled drawers versus numbered ones. Instead of remembering "the third drawer holds socks," you just look for the drawer labeled "socks."
Using group(String name)
After a successful find() or matches() call, pass the group's name as a String to the group() method:
Pattern pattern = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})");
Matcher matcher = pattern.matcher("2024-03-15");
if (matcher.matches()) {
String year = matcher.group("year"); // "2024"
String month = matcher.group("month"); // "03"
String day = matcher.group("day"); // "15"
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day: " + day);
}
Why This Matters
Named access eliminates mental overhead. Compare matcher.group(1), matcher.group(2), matcher.group(3) (which requires you to count parentheses) with matcher.group("year"), matcher.group("month"), matcher.group("day") (which reads like natural language).
It's especially valuable when maintaining complex patterns where adding a new group would otherwise shift all the indexes.
Key Takeaway: Use matcher.group("groupName") to retrieve captured text by name, making your regex extraction code clearer and more maintainable than numeric indexing.