Pattern.matcher()
Creates a Matcher that searches for the pattern in a specific string.
Available since: Java 1.4
Syntax
public Matcher matcher(CharSequence input)Parameters
| Parameter | Type | Description |
|---|---|---|
| input | CharSequence | The string to search in. |
Return value
MatcherA new Matcher with find(), matches(), group(), replaceAll().
Examples
The typical chain — compile, matcher, find:
void main() {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Room 42, floor 7");
while (matcher.find()) {
IO.println(matcher.group());
}
}Output:
42
7Notes
A Matcher keeps search state (the current position), so do not share it between threads. For a new string create a new Matcher or call matcher.reset(newInput).
See also
- Pattern.compile() — Compiles a regular expression into a Pattern object that can be reused many times.
- Matcher.find() — Searches for the next match of the pattern anywhere in the string.
- Matcher.matches() — Checks whether the whole string matches the pattern.
- Matcher.group() — Returns the text of the current match or of one of its parenthesized groups.
In the tutorial
- Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.