regex
Matcher start example
In this example we shall show you how to use Matcher.start() API method to get the start index of the previous match of a sequence against a pattern. To use Matcher.start() 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 next subsequence of the input sequence that matches the pattern it returns it, using
find()API method of Matcher. - Get the start index of the first match, with
start()API method of Matcher. - Find the next subsequence, and again the start index of the second match.
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[]) {
String str = "My name is Bond. James Bond.";
String mHelp[] = {"
^", "
^"};
Pattern pattern = Pattern.compile("Bond");
Matcher m = pattern.matcher(str);
//Find the starting point of the first 'Bond'
m.find();
int sIndex = m.start();
System.out.println(str);
System.out.println(mHelp[0] + sIndex);
//Find the starting point of the second 'Bond'
m.find();
int nIndex = m.start();
System.out.println(str);
System.out.println(mHelp[1] + nIndex);
}
}
Output:
My name is Bond. James Bond.
^11
My name is Bond. James Bond.
^23
This was an example of Matcher.start() API method in Java.

