Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Matcher — checking text and reading matches

java.util.regex.Matcher applies a regular expression to text. matches() checks the entire region, find() searches for successive substrings, and group() reads the result of a successful match.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
boolean whole = matcher.matches();
matcher.reset();
while (matcher.find()) {
    String match = matcher.group();
    // groupCount() counts capturing groups in the pattern, excluding group 0.
    // This guard checks that group 1 exists, not that it participated in the match.
    if (matcher.groupCount() >= 1) {
        String captured = matcher.group(1);
    }
}

java.util.regex.Matcher matches a Pattern against text. Create it with pattern.matcher(input). The object retains search state; do not share it between threads.

Matcher.matches() checks the entire current region, which defaults to the entire input. Matcher.find() searches for the next matching substring; repeated calls advance the search. Both methods return boolean. reset() discards match state and restores the region to the entire input.

Matcher.group() and group(0) return the whole match. Capturing groups are numbered from 1 in opening-parenthesis order: group(1) reads the first. Read a named group with group("name"). An optional group that did not participate returns null, whereas a group matching empty text returns "".

Read groups after a true result: before a match attempt or after a failed attempt, group() throws IllegalStateException. In the example, matches() returns false because the pattern does not cover the entire input; after reset(), the find() loop reads two matches and their groups.

Examples

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("([A-Z]+)-([0-9]+)");
        Matcher matcher = pattern.matcher("AB-12 CD-7");

        System.out.println("matches=" + matcher.matches());
        matcher.reset();
        while (matcher.find()) {
            System.out.println(matcher.group() + " | "
                    + matcher.group(1) + " | " + matcher.group(2));
        }
    }
}

Result

matches=false
AB-12 | AB | 12
CD-7 | CD | 7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources