Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Regex Groups: Capturing and Named Groups

Learn how to use capturing groups, named groups, and backreferences in Java regex with practical examples.

~4 min readJava
#regex#capturing groups#named groups#Pattern
Diagram showing a regex pattern with highlighted capturing groups and named groups in Java

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.

java
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.

java
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).

java
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.

java
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.

java
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.

java
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.

java
// 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 tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.