CKTIS / Java
Matcher.group() and Matcher.group(int): the whole match and captures
After a successful regex match, read the whole matched text or the text captured by a specific group. Group 0 is the whole match.
Version: Java SE 21
Syntax
public String group()
public String group(int group)In Java SE 21, java.util.regex.Matcher has three group overloads that return String. This entry covers group() and group(int); the third overload, group(String), returns the text captured by a named group. Matcher.group() returns the entire matched part of the input and is equivalent to group(0). Matcher.group(int) with an index from 1 through groupCount() returns the text captured by that group. Capturing groups are numbered by their opening parentheses from left to right. A non-capturing group (?:...) gets no number, and group 0 is not included in groupCount().
Read groups after matches(), find(), or lookingAt() returns true. matches() checks the entire current input region, find() searches for the next matching part, and lookingAt() checks for a match at the start of the region without requiring it to cover the whole region. The group methods do not run a match. Read the values you need before the next attempt or a call to reset().
If the overall match succeeded but the selected group did not participate, group(int) returns null. If the group participated and matched zero characters, it returns the empty string "". Before any match attempt, after a failed attempt, or after reset() with no new attempt, both overloads throw IllegalStateException. With valid match state, an out-of-range index throws IndexOutOfBoundsException. Changing the pattern with usePattern(...) after a successful match discards group data; before another attempt, either overload can return null.
Examples
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(ID)-([0-9]+)([A-Z])?([ ]*)");
Matcher matcher = pattern.matcher("item: ID-42");
if (matcher.find()) {
System.out.println("group() = [" + matcher.group() + "]");
System.out.println("group(0) = [" + matcher.group(0) + "]");
System.out.println("group(1) = [" + matcher.group(1) + "]");
System.out.println("group(2) = [" + matcher.group(2) + "]");
System.out.println("group(3) = " + matcher.group(3));
System.out.println("group(4) = [" + matcher.group(4) + "]");
}
}
}Result
group() = [ID-42] group(0) = [ID-42] group(1) = [ID] group(2) = [42] group(3) = null group(4) = []
`find()` locates `ID-42` within `item: ID-42`. Group 3 does not participate because there is no optional letter. Group 4 matches zero spaces, so `[]` shows an empty string.
Related lessons
- Java · Lesson 70 · Basic · Version: 2