CKTIS / Java
Pattern.matcher — Create a matcher for an input
`Pattern.matcher` creates a new `Matcher` for the given input. Reuse one compiled pattern across multiple texts while keeping their matching state separate.
Version: Java SE 21
Syntax
public Matcher matcher(CharSequence input)
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);Pattern.matcher(CharSequence input) is an instance method of Pattern in java.util.regex. First compile the regular expression with Pattern.compile(regex), then call pattern.matcher(input) on the resulting pattern. The argument, such as a String, is the text to check, not the regular expression. Passing null throws NullPointerException.
Each call returns a new Matcher without trying to match yet. find() searches for the next matching substring, lookingAt() tries to match from the start of the region, and matches() tests the entire region. By default, the region covers the entire input. All three methods return a boolean.
After a successful match, group() returns the entire matched substring. Calling it before the first match attempt or after a failed attempt throws IllegalStateException. In a loop, call group() only when find() returns true.
A Pattern is immutable and can be shared across threads. A Matcher holds mutable matching state and is not safe for concurrent use. Create separate matchers when you need independent state. reset() keeps the input, while reset(newInput) changes it; both discard the previous result and restore the region to the entire input.
Examples
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern digits = Pattern.compile("[0-9]+");
Matcher scan = digits.matcher("A12 B34");
Matcher whole = digits.matcher("56");
while (scan.find()) {
System.out.println(scan.group());
}
System.out.println(whole.matches());
}
}Result
12 34 true
`[0-9]+` matches one or more consecutive ASCII digits. The first `Matcher` prints `12` and `34`. The second uses the same pattern and prints `true` because its entire input, `56`, matches.
Related lessons
- Java · Lesson 70 · Basic · Version: 2