Java Matcher find() Method
Example
Find all numbers in a sentence:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher("The binary representation of 5 is 101.");
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Definition and Usage
The find() method searches the text for the next part that matches the pattern.
Each call continues where the last match ended, so you can call it in a loop to find all matches. In the example, [0-9]+ means "one or more digits from 0 to 9".
Tip: Use the group() method to get the text that was found.
Syntax
One of the following:
public boolean find()
public boolean find(int start)
Parameter Values
| Parameter | Description |
|---|---|
| start | Optional. The index (position) in the text where the search starts. The matcher is reset first. |
Technical Details
| Returns: | true if a match was found, otherwise false. |
|---|---|
| Throws: | IndexOutOfBoundsException - if start is less than 0 or greater than the length of the text. |
Related Pages
❮ RegEx Methods