Accessing Captured Text with group(int)
What you'll learn: How to retrieve the specific text matched by individual capturing groups in your regular expression.
Now that you understand capturing groups and their numbering, you need a way to actually extract the text they captured. The Matcher.group(int) method does exactly that—it returns the substring matched by a specific capturing group after a successful match operation.
How group(int) Works
After calling find(), matches(), or lookingAt() and getting a successful match, you can call group(int) with a group number:
group(0)returns the entire matched text (same asgroup()with no argument)group(1)returns the text captured by the first set of parenthesesgroup(2)returns the text captured by the second set of parentheses- And so on...
Think of capturing groups like labeled containers. When the regex engine finds a match, it fills these containers with the text each group captured. The group(int) method lets you peek inside any container by its number.
Example Usage
Pattern pattern = Pattern.compile("(\\d{3})-(\\d{4})");
Matcher matcher = pattern.matcher("Call me at 555-1234");
if (matcher.find()) {
String fullMatch = matcher.group(0); // "555-1234"
String areaCode = matcher.group(1); // "555"
String number = matcher.group(2); // "1234"
System.out.println("Area code: " + areaCode);
System.out.println("Number: " + number);
}
Important Notes
You must call a matching method (find(), matches(), or lookingAt()) successfully before calling group(int), or you'll get an IllegalStateException. Also, requesting a group number that doesn't exist throws an IndexOutOfBoundsException.
Key Takeaway: Use Matcher.group(int) to extract the text captured by specific numbered groups in your pattern, enabling precise data extraction from matched strings.