What Are Groups in Regular Expressions?
You'll learn how parentheses create groups in regex patterns to isolate and extract specific parts of matched text.
Understanding Groups
In regular expressions, groups are portions of a pattern enclosed in parentheses (). They serve two primary purposes: they let you apply quantifiers to multiple characters as a unit, and more importantly, they let you capture and extract specific substrings from your matches.
Think of groups like highlighting portions of a document. When you find a match, groups let you ask "What was the text in the first highlighted section? The second?" instead of just "Did this match?"
How Groups Work
When you use parentheses in a regex pattern, the Matcher remembers what text matched inside those parentheses. Each set of parentheses creates a numbered group, starting from 1 (group 0 is always the entire match).
For example, the pattern (\d{3})-(\d{4}) matches phone number endings like "555-1234":
- Group 0: The entire match "555-1234"
- Group 1: The first three digits "555"
- Group 2: The last four digits "1234"
Accessing Captured Groups
After a successful find() or matches(), you retrieve group content using the group(int) method:
group(0)orgroup()returns the entire matched textgroup(1)returns the first captured groupgroup(2)returns the second captured group, and so on
Groups let you parse structured data from text. Instead of just knowing "this looks like a phone number," you can extract the area code and local number separately.
Key Takeaway: Groups in regex use parentheses to capture and isolate parts of a match, enabling precise extraction of substrings through the group() method on a Matcher object.