Multiple Captures in One Pattern
You'll learn how to extract several pieces of information from a single string using multiple capturing groups in one regular expression.
The Power of Multiple Groups
Rather than running multiple regex operations or parsing manually, you can define several capturing groups within a single pattern. Each set of parentheses () creates a numbered group, letting you pull out distinct pieces of data in one pass.
Think of it like a form with multiple fields: instead of reading the document once per field, you identify all the blanks in one template and fill them simultaneously.
How It Works
When your pattern contains multiple () pairs, the Matcher assigns each a sequential number (starting at 1). After a successful match, you access each captured piece via group(1), group(2), etc.
Pattern pattern = Pattern.compile("(\\w+)@(\\w+)\\.(\\w+)");
Matcher matcher = pattern.matcher("john@example.com");
if (matcher.find()) {
System.out.println("Username: " + matcher.group(1)); // john
System.out.println("Domain: " + matcher.group(2)); // example
System.out.println("TLD: " + matcher.group(3)); // com
}
Here, three capturing groups extract the username, domain name, and top-level domain from an email address—all in one match operation.
Parsing Structured Data
This technique shines when parsing log entries, dates, or any formatted text:
Pattern datePattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher dateMatcher = datePattern.matcher("2024-03-15");
if (dateMatcher.matches()) {
String year = dateMatcher.group(1); // 2024
String month = dateMatcher.group(2); // 03
String day = dateMatcher.group(3); // 15
}
Key Takeaway: Multiple capturing groups in one pattern let you extract several related pieces of information simultaneously, making data extraction efficient and your code cleaner.