Java Regex Groups: Capturing and Named Groups
Learn how to use capturing groups, named groups, and backreferences in Java regex with practical examples.

When you work with groups in Java regex, the numbering and naming of groups determine how you extract data from a matched string. A capturing group is a portion of the pattern enclosed in parentheses that records the substring matched by that part of the pattern. The entire match is always group 0, and each capturing group is numbered from 1 onward in the order its opening parenthesis appears. Misunderstanding this numbering is a common source of bugs when extracting values from regex matches.
How Capturing Groups Work in Java Regex
A capturing group is defined by parentheses in the pattern. For example, the pattern (\d{4})-(\d{2}) has two groups: the first captures four digits, the second captures two digits. When the regex engine matches a string, it records the substring matched by each group. The Matcher object exposes these groups through the group(int) method.
Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})");
Matcher matcher = pattern.matcher("2024-07");
if (matcher.matches()) {
System.out.println(matcher.group(0)); // 2024-07
System.out.println(matcher.group(1)); // 2024
System.out.println(matcher.group(2)); // 07
}Accessing Groups with Matcher
The Matcher class provides several methods to work with groups. group() returns the entire match, equivalent to group(0). group(int group) returns the substring captured by the specified group, or null if that group did not participate in the match. groupCount() tells you how many capturing groups exist in the pattern.
Pattern pattern = Pattern.compile("(\\w+)@(\\w+\\.\\w+)");
Matcher matcher = pattern.matcher("user@example.com");
if (matcher.matches()) {
System.out.println("Groups: " + matcher.groupCount()); // 2
System.out.println("User: " + matcher.group(1));
System.out.println("Domain: " + matcher.group(2));
}A common mistake is calling group() before a successful match. The Matcher is stateful, and methods like find() or matches() must be called first. Calling group() after a failed match throws IllegalStateException.
Named Capturing Groups
Java 7 introduced named capturing groups, which make patterns more readable and reduce errors when groups are reordered. The syntax is (?<name>...). You can retrieve the captured value using group(String name).
Pattern pattern = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})");
Matcher matcher = pattern.matcher("2024-07");
if (matcher.matches()) {
System.out.println(matcher.group("year")); // 2024
System.out.println(matcher.group("month")); // 07
}Named groups are especially useful in complex patterns where positional numbering becomes hard to track. They also make the code self-documenting. The name can contain letters, digits, and underscores, cannot begin with a digit, and duplicate names are not allowed within the same pattern.
Non-Capturing Groups and When to Use Them
Not every parenthesis needs to capture. If you need to group tokens for alternation or repetition but do not need the captured value, use a non-capturing group with (?:...). This avoids creating an extra group number and slightly reduces overhead.
Pattern pattern = Pattern.compile("(?:ab|cd)+-");
Matcher matcher = pattern.matcher("ababcd-");
if (matcher.matches()) {
System.out.println("Matched: " + matcher.group());
System.out.println("Group count: " + matcher.groupCount()); // 0
}Non-capturing groups are useful when you apply quantifiers or alternation to a subexpression without polluting the group list. For example, (?:\d{3}-)?\d{4} makes the first three digits optional without creating a group that you would have to ignore.
Backreferences and Group Reuse in Patterns
Backreferences allow you to match the same text that a group previously captured. In Java regex, you reference a group by its number with \1, \2, etc., or by its name with \k<name>. This is useful for finding repeated words, matching paired delimiters, or validating consistent formatting.
Pattern pattern = Pattern.compile("(\\w+) \\1");
Matcher matcher = pattern.matcher("hello hello");
if (matcher.matches()) {
System.out.println("Repeated word: " + matcher.group(1));
}Named backreferences use the syntax \k<name>. For example, (?<quote>['"]).*?\k<quote> matches a string enclosed in either single or double quotes, ensuring the closing quote matches the opening one. Backreferences operate on the captured text, not the pattern, so they are evaluated at runtime.
Common Pitfalls with Group Indexing
Group numbering is based on the opening parenthesis position, not the closing one. Nested groups can be confusing. Consider the pattern ((a)(b)). The outer group is 1, then a is group 2, and b is group 3. When you use alternation, groups that do not participate in a match return null.
Pattern pattern = Pattern.compile("(a)|(b)");
Matcher matcher = pattern.matcher("a");
if (matcher.matches()) {
System.out.println(matcher.group(1)); // a
System.out.println(matcher.group(2)); // null
}Another pitfall is using matches() when you need find(). matches() requires the entire input to match the pattern, while find() scans for the next occurrence. If you use matches() with a pattern that only matches part of the string, the match fails and you cannot read groups from that call. Always choose the method that matches your intent.
Performance Considerations for Group Matching
Capturing groups add some overhead because the regex engine has to track the start and end position of each captured group. If you do not need the captured values, avoid capturing groups to reduce that overhead. This is particularly relevant in tight loops or when processing large text volumes.
// Captures values you do not need
Pattern withGroups = Pattern.compile("(\\d+)-(\\d+)-(\\d+)");
// Matches the same input pattern, but creates no groups
Pattern withoutGroups = Pattern.compile("\\d+-\\d+-\\d+");If you still need parentheses for grouping, use a non-capturing group such as (?:...) rather than a capturing group.
Reusing a compiled Pattern is also important. Compiling a regex for each match repeats the parsing and setup work. In a loop, compile once outside the loop and reuse the Matcher with reset() if needed. Backreferences are generally more expensive than plain groups because they require runtime comparison of captured text, but the impact is negligible for typical inputs. For high-throughput scenarios, measure with realistic data rather than assuming the overhead is significant.
When you design a pattern, decide whether each group needs to capture. If a group exists only for grouping, make it non-capturing. This keeps the group indices predictable and reduces the amount of state the engine tracks. The result is cleaner code and slightly faster matching, especially when the pattern is applied many times.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.