The match() method of java.util.Scanner class returns the match result of the last scanning operation performed by this scanner.
Syntax:
public MatchResult match()
Return Value: This function returns a match result for the last match operation.
Exceptions: The function throws IllegalStateException if no match has been performed, or if the last match was not successful.
Below programs illustrate the above function:
Program 1:
// Java program to illustrate the // match() method of Scanner class in Java // without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "GFG Geeks!" ; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // check if next token is "GFG" System.out.println( "" + scanner.hasNext( "GFG" )); // find the last match and print it System.out.println( "" + scanner.match()); // print the line System.out.println( "" + scanner.nextLine()); // close the scanner scanner.close(); } } |
true java.util.regex.Matcher[pattern=GFG region=0, 10 lastmatch=GFG] GFG Geeks!
Program 2: To demonstrate IllegalStateException
// Java program to illustrate the // match() method of Scanner class in Java // without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "GFG Geeks!" ; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // check if next token is "gopal" System.out.println( "" + scanner.hasNext( "gopal" )); // find the last match and print it System.out.println( "" + scanner.match()); // print the line System.out.println( "" + scanner.nextLine()); // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println( "Exception caught is: " + e); } } } |
false Exception caught is: java.lang.IllegalStateException: No match result available
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#match()