Java Matcher start() Method
Example
Find "w3schools" in a sentence, and get the index where the match starts:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
if (matcher.find()) {
System.out.println(matcher.start());
}
}
}
Definition and Usage
The start() method returns the index (position) of the first character of the match.
The first character in a text has index 0. In the example, the match W3Schools starts at index 6. Use it after a successful call to find(), matches() or lookingAt().
Tip: Use the end() method to get the index after the last character of the match.
Syntax
One of the following:
public int start()
public int start(int group)
public int start(String name)
Parameter Values
| Parameter | Description |
|---|---|
| group | Optional. The number of a group in the pattern. The method then returns the start of that group. |
| name | Optional. The name of a named group in the pattern. |
Technical Details
| Returns: | The index of the first character of the match, as an int. |
|---|---|
| Throws: | IllegalStateException - if no match has been found. |
Related Pages
❮ RegEx Methods