Working with Matcher.start() method in Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

The start index of the subsequence that was found by the group during the previous match operation is returned by the method java.util.regex.Matcher.start(). This method has a single argument i.e.the capturing group’s index for the specified pattern.

A program that demonstrates the method Matcher.start() Java regular expressions is given as follows:

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("(a*b)");
      Matcher m = p.matcher("caaabccaab");
      System.out.println("The input string is: caaabccaab");
      System.out.println("The Regex is: (a*b)");
      System.out.println();
      while (m.find()) {
         System.out.println("Index: " + m.start(1));
      }
   }
}

Output

The input string is: caaabccaab
The Regex is: (a*b)
Index: 1
Index: 7

Now let us understand the above program.

The subsequence “(a*b)” is searched in the string sequence "caaabccaab". The find() method is used to find if the subsequence is in the input sequence and the start index of the subsequence that was found by the group during the previous match operation is printed using the start() method. A code snippet which demonstrates this is as follows:

Pattern p = Pattern.compile("(a*b)");
Matcher m = p.matcher("caaabccaab");
System.out.println("The input string is: caaabccaab");
System.out.println("The Regex is: (a*b)");
System.out.println();
while(m.find()) {
   System.out.println("Index: " + m.start(1));
}
raja
Published on 19-Feb-2019 06:16:35
Advertisements