Determining the position and length of the match Java regex


The start() method of the java.util.regex.Matcher class returns the starting position of the match (if a match occurred).

Similarly, the end() method of the Matcher class returns the ending position of the match.

Therefore, return value of the start() method will be the starting position of the match and the difference between the return values of the end() and start() methods will be the length of the match.

Example

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
   public static void main(String[] args) {
      int start = 0, len = -1;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\d+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         start = matcher.start();
         len = matcher.end()-start;
      }
      System.out.println("Position of the match : "+start);
      System.out.println("Length of the match : "+len);
   }
}

Output

Enter input text:
sample data with digits 12345
Position of the match : 24
Length of the match : 5

Updated on: 13-Jan-2020

828 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements