Matcher hitEnd() method in Java with Examples


The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.

The hitEnd() method verifies whether the end of the input data reached during the previous match if so, it returns true else false. If this method returns true it indicates that more input data might change the result of the match.

For example, if you are trying to match the last word of an input string to you using the regex “you$” and if your 1st input line is “hello how are you” you might have a match but, if you accept more sentences the last word of the new line(s) may not be the required word (which is “you”), making your match result false. In such cases, the hitEnd() method returns true.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HitEndExample {
   public static void main( String args[] ) {
      String regex = "you$";
      //Reading input from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      //Instantiating the Pattern class
      Pattern pattern = Pattern.compile(regex);
      //Instantiating the Matcher class
      Matcher matcher = pattern.matcher(input);
      //verifying whether a match occurred
      if(matcher.find()) {
         System.out.println("Match found");
      }
      boolean result = matcher.hitEnd();
      if(result) {
         System.out.println("More input may turn the result of the match false");
      } else {
         System.out.println("The result of the match will be true, inspite of more data");
      }
   }
}

Output

Enter input text:
Hello how are you
Match found
More input may turn the result of the match false

Updated on: 20-Nov-2019

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements