CKTIS / Java
Matcher.find: searching for successive matches
Use `find()` to search for successive regex matches, or `find(int start)` to restart the search at a specified input index.
Version: Java SE 21
Syntax
public boolean find()
public boolean find(int start)Matcher.find is an instance method of java.util.regex.Matcher. Create a Matcher with pattern.matcher(input). On a new or reset matcher, find() starts at the beginning of the region, which covers the entire input by default. Reuse the same matcher in while (matcher.find()): after a nonempty match, the next search starts just after it. true means a match was found, even if it is empty; false means no next match was found.
After true, use group() for the whole matched text, start() for its inclusive start, and end() for its exclusive end. Indices are zero-based and relative to the full input. Read the result before trying another match: the API specifies IllegalStateException for these methods before any match has been attempted or after a failed attempt.
find(int start) resets the matcher, restores the region to the full input, and searches at or after start. It does not require a match exactly at that index. It throws IndexOutOfBoundsException if start is negative or greater than the input length. To continue the search, call find() without an argument; find(int start) restarts it each time.
lookingAt() requires a match at the beginning of the region but need not match all of it. matches() requires the entire region to match. Use find() to search anywhere in the region that the pattern allows.
Examples
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Matcher matcher = Pattern.compile("[0-9]+").matcher("A12 B7");
while (matcher.find()) {
System.out.println(matcher.group() + " [" + matcher.start()
+ ", " + matcher.end() + ")");
}
if (matcher.find(4)) {
System.out.println("find(4): " + matcher.group());
}
}
}Result
12 [1, 3) 7 [5, 6) find(4): 7
`[0-9]+` matches runs of one or more ASCII digits. The loop prints `12` and `7` with their ranges. After the loop, `find(4)` starts at `B` and finds `7` at index `5`.
Related lessons
- Java · Lesson 70 · Basic · Version: 2