regex
Matcher start with parameter example
This is an example of how to use Matcher.start(int group)
API method to get the start index of the subsequence captured by the given group during the previous match operation. Using Matcher.start(int group)
implies that you should:
- 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 start index of the subsequence captured by the given group during the previous match operation with
start(int group)
API method. Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expressionm.start(0)
is equivalent tom.start()
. - Get the start index of the subsequence captured by the next group during the previous match operation, with parameter int group set to 1.
- Find the next subsequence of the input sequence that matches the pattern and again get the starting points of the groups as above.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherStart { public static void main(String args[]) { Pattern pattern = Pattern.compile("B(ond)"); String str = "My name is Bond. James Bond."; String matchHelper[] = {" ^", " ^", " ^", " ^"}; Matcher m = pattern.matcher(str); m.find(); int sIndex = m.start(0); System.out.println(str); System.out.println(matchHelper[0] + sIndex); int nIndex = m.start(1); System.out.println(str); System.out.println(matchHelper[1] + nIndex); m.find(); sIndex = m.start(0); System.out.println(str); System.out.println(matchHelper[2] + sIndex); nIndex = m.start(1); System.out.println(str); System.out.println(matchHelper[3] + nIndex); } }
Output:
My name is Bond. James Bond.
^11
My name is Bond. James Bond.
^12
My name is Bond. James Bond.
^23
My name is Bond. James Bond.
^24
This was an example of Matcher.start(int group)
API method in Java.