Java Matcher end() Method
Example
Find "w3schools" in a sentence, and get the index where the match ends:
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.end());
}
}
}
Definition and Usage
The end() method returns the index (position) after the last character of the match.
The first character in a text has index 0. In the example, the last character of the match W3Schools has index 14, so end() returns 15. Use it after a successful call to find(), matches() or lookingAt().
Tip: Use the start() method to get the index of the first character of the match.
Syntax
One of the following:
public int end()
public int end(int group)
public int end(String name)
Parameter Values
| Parameter | Description |
|---|---|
| group | Optional. The number of a group in the pattern. The method then returns the end of that group. |
| name | Optional. The name of a named group in the pattern. |
Technical Details
| Returns: | The index after the last character of the match, as an int. |
|---|---|
| Throws: | IllegalStateException - if no match has been found. |
Related Pages
❮ RegEx Methods