regex
Matcher end with parameter example
In this example we shall show you how to use Matcher.end(int group)
API method to get the offset after the last character of the subsequence captured by the given group, during the previous match operation. To use Matcher.end(int group)
one should perform the following steps:
- Compile a String regular expression to a Pattern, using
compile(String regex)
API method of Pattern. - Use an initial String to be matched against the Pattern.
- Use
matcher(CharSequence input)
API method of Pattern to create a Matcher that will match the given String input against this pattern. - Find the first subsequence of the input sequence that matches the pattern, using
find()
API method of Matcher. - Get the offset after the last character of the subsequence captured by the given group during the previous match operation, with
end(int group)
API method. Group zero denotes the entire pattern, so the expressionm.end(0)
is equivalent tom.end()
. - Use
end(int group)
API method again to get the offset after the last character of the subsequence captured by the specified group during the previous match operation, setting the int group parameter to 1. - Find the next subsequence of the input sequence that matches the pattern, and again get the offset after the last character of the subsequence captured by the entire pattern and by the group 1,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherEnd { public static void main(String args[]) { Pattern pattern = Pattern.compile("B(on)d"); String str = "My name is Bond. James Bond."; String mHelper[] = {" ^", " ^", " ^", " ^"}; Matcher m = pattern.matcher(str); m.find(); int end = m.end(0); System.out.println(str); System.out.println(mHelper[0] + end); int next = m.end(1); System.out.println(str); System.out.println(mHelper[1] + next); m.find(); end = m.end(0); System.out.println(str); System.out.println(mHelper[2] + end); next = m.end(1); System.out.println(str); System.out.println(mHelper[3] + next); } }
Output:
My name is Bond. James Bond.
^15
My name is Bond. James Bond.
^14
My name is Bond. James Bond.
^27
My name is Bond. James Bond.
^26
This was an example of Matcher.end(int group)
API method in Java.