The start() method of the Matcher class is used to return the starting index of the most recent match found by the find() method. It helps identify the exact position where a matching pattern begins in the input string.
- Must be called after a successful find() or matches() operation.
- Returns an integer representing the first character's index.
- Throws IllegalStateException if no successful match exists.
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher("Learn Java Programming");
if (matcher.find()) {
System.out.println("Start Index: " + matcher.start());
}
}
}
Output
Start Index: 6
Explanation: The word "Java" starts at index 6 in the string "Learn Java Programming", so start() returns 6.
Syntax
public int start()
Returns
- An integer representing the starting index of the matched substring.
Exception
- IllegalStateException: Thrown if no match has been attempted or the previous match failed.
Example 1: Java code to illustrate start() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args) {
// Regex pattern
String regex = "(G*k)";
// Create Pattern object
Pattern pattern = Pattern.compile(regex);
// Input string
String stringToBeMatched = "Geeks";
// Create Matcher object
Matcher matcher = pattern.matcher(stringToBeMatched);
// Find matches and print starting index
while (matcher.find()) {
System.out.println("Matched Text: " + matcher.group());
System.out.println("Start Index: " + matcher.start());
}
}
}
Output
Matched Text: k Start Index: 3
Explanation: In this example, the regex (G*k) matches the character k in the string "Geeks". The find() method locates the match, and start() returns its starting index, which is 3.
Example 2:
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Get the regex to be checked
String regex = "(G*G)";
// Create a pattern from regex
Pattern pattern
= Pattern.compile(regex);
// Get the String to be matched
String stringToBeMatched = "GFG";
// Create a matcher for the input String
Matcher matcher
= pattern
.matcher(stringToBeMatched);
// Get the current matcher state
MatchResult result
= matcher.toMatchResult();
System.out.println("Current Matcher: "
+ result);
while (matcher.find()) {
// Get the first index of match result
System.out.println(matcher.start());
}
}
}
Output
Current Matcher: java.util.regex.Matcher$ImmutableMatchResult@1dbd16a6 0 2
Explanation: The pattern (G*G) matches the character 'G' at two positions in the string "GFG". The first match starts at index 0, and the second match starts at index 2, so start() returns 0 and 2.