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

Combining find() with Groups for Data Extraction

Learn how find() combined with capturing groups allows you to extract specific data from complex strings efficiently.

Combining find() with Groups for Data Extraction

What you'll learn: How to use find() with capturing groups to extract specific pieces of data from within complex strings.


When searching through text, you often don't just want to know if a pattern exists—you want to pull out specific pieces of information. By combining find() with capturing groups (parentheses in your regex), you can pinpoint and extract exactly the data you need from each match.

The Core Idea

Think of find() as a spotlight that scans through your string looking for patterns. Capturing groups are like labeled buckets within that spotlight—each set of parentheses captures a specific portion of the match. After find() returns true, you can call group(1), group(2), etc., to retrieve what each bucket captured.

How It Works

The group(0) or group() returns the entire matched substring. But group(1) returns what the first set of parentheses captured, group(2) returns the second set, and so on.

Pattern pattern = Pattern.compile("(\\d{3})-(\\d{2})-(\\d{4})");
Matcher matcher = pattern.matcher("My SSN is 123-45-6789 and hers is 987-65-4321");

while (matcher.find()) {
    String fullMatch = matcher.group(0);  // "123-45-6789"
    String area = matcher.group(1);        // "123"
    String group = matcher.group(2);       // "45"
    String serial = matcher.group(3);      // "4789"
    
    System.out.println("Found: " + fullMatch);
    System.out.println("  Area: " + area + ", Group: " + group + ", Serial: " + serial);
}

This extracts each SSN's components in one pass. The loop continues finding matches, and each time you can dissect the match using the numbered groups.

Key Takeaway: Combining find() with capturing groups transforms pattern matching from simple detection into surgical data extraction, letting you parse complex strings and pull out exactly the fields you need.