MatchResult start() method in Java with examples.


The java.util.regex.MatcheResult interface provides methods to retrieve the results of a match.

You can get an object of this interface using the toMatchResult() method of the Matcher class. This method returns a MatchResult object which represents the match state of the current matcher.

The start() method of this interface returns the beginning index of the current match.

Example

 Live Demo

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\W";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      }else {
         System.out.println("Match not occurred");
      }
      //Retrieving the MatchResult object
      MatchResult res = matcher.toMatchResult();
      int start = res.start();
      System.out.println(start);
   }
}

Output

Enter a String
This * is # sample % text with & non word characters
Match occurred
4

Updated on: 10-Jan-2020

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements