Course contentsShow
← Java
Lesson 2276 of 2,87044. Regular ExpressionsFree lesson

Multiple Named Groups in One Pattern

Create patterns with several named groups to extract multiple pieces of structured data from a single match.

Multiple Named Groups in One Pattern

What you'll learn: How to define and use several named capturing groups in a single regular expression to extract multiple related pieces of data at once.


The Core Idea

Just as you can have multiple numbered groups in a pattern, you can also define multiple named groups. This is incredibly powerful for parsing structured text like dates, log entries, or formatted records. Instead of remembering "group 1 is the year, group 2 is the month," you can extract values by meaningful names like year and month.

How It Works

Use the (?<name>...) syntax multiple times within your pattern. Each name must be unique. When the matcher finds a match, you can retrieve each captured piece using group("name").

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 + ", Month: " + month + ", Day: " + day);
}

Think of It Like a Form

Imagine a pattern as a form template with labeled fields. Instead of "Field 1, Field 2, Field 3," you have "FirstName, LastName, Email." Multiple named groups let you label each piece of data you want to extract, making your code self-documenting and much easier to maintain.

Practical Example: Parsing Log Entries

Pattern logPattern = Pattern.compile(
    "\\[(?<timestamp>[^\\]]+)\\] (?<level>\\w+): (?<message>.*)"
);
Matcher logMatcher = logPattern.matcher("[2024-03-15 10:30:45] ERROR: Connection timeout");

if (logMatcher.matches()) {
    String timestamp = logMatcher.group("timestamp");
    String level = logMatcher.group("level");
    String message = logMatcher.group("message");
}

Key Takeaway: Multiple named groups transform complex patterns into readable, self-documenting extractors—use descriptive names for each piece of data you want to capture, and your code becomes instantly more maintainable.