Named Capturing Groups Syntax
You'll learn how to assign meaningful names to capturing groups using (?<name>...) syntax, making complex patterns easier to read and maintain.
Beyond Numbers: Why Named Groups Matter
You've been working with numbered groups like group(1), group(2), etc., but what does "group 2" actually represent in a complex pattern? Named groups solve this readability problem by letting you refer to captures by descriptive identifiers instead of remembering which number corresponds to which piece of data.
The Named Group Syntax
Instead of plain parentheses (...), use the special syntax:
(?<name>pattern)
The angle brackets contain your chosen identifier, followed by the pattern you want to capture.
Accessing Named Groups
Once you've defined a named group, retrieve it using group(String name) instead of group(int):
Pattern p = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})");
Matcher m = p.matcher("2024-03-15");
if (m.matches()) {
String year = m.group("year"); // "2024"
String month = m.group("month"); // "03"
String day = m.group("day"); // "15"
}
Notice how m.group("year") is far more self-documenting than m.group(1).
Mixing Named and Numbered Access
Named groups still have numeric indices—you can access the same capture using either the name or its group number. The numbering works exactly as before (left-to-right opening parentheses).
When to Use Named Groups
Use named groups when patterns get complex or when you're extracting multiple structured fields. They make code maintenance easier and reduce counting errors in group indices.
Key Takeaway:
Named capturing groups use (?<name>...) syntax to assign meaningful identifiers to captures, accessed via group("name") for clearer, more maintainable regex code.