Iterating through a few examples will allow you to clear the functioning of matcher.find() :
The Regex engine takes one character from a string (i.e. ababa) and tries to find if the pattern you are looking for in the string can be found or not. If the template exists, then (as mentioned in the API):
matcher.start () returns the starting index, matcher.end () returns the offset after matching the last character.
If a match does not exist. then start () and end () return the same index that should correspond to the agreed length is zero.
Look down the following examples:
// Searching for string either "a" or "" Pattern pattern = Pattern.compile("a?"); Matcher matcher = pattern.matcher("abaabbbb"); while(matcher.find()){ System.out.println(matcher.start()+"["+matcher.group()+"]"+matcher.end()); }
Output:
0[a]1 1[]1 2[a]3 3[a]4 4[]4 5[]5 6[]6 7[]7 8[]8 // Searching for string either "aa" or "a" Pattern pattern = Pattern.compile("aa?"); Matcher matcher = pattern.matcher("abaabbbb"); while(matcher.find()){ System.out.println(matcher.start()+"["+matcher.group()+"]"+matcher.end()); }
Output:
0[a]1 2[aa]4
Rohit bansal
source share