Scanner match() method in Java with Example
Last Updated :
16 Oct, 2018
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:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
String s = "GFG Geeks!" ;
Scanner scanner = new Scanner(s);
System.out.println( "" + scanner.hasNext( "GFG" ));
System.out.println( "" + scanner.match());
System.out.println( "" + scanner.nextLine());
scanner.close();
}
}
|
Output:
true
java.util.regex.Matcher[pattern=GFG region=0, 10 lastmatch=GFG]
GFG Geeks!
Program 2: To demonstrate IllegalStateException
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "GFG Geeks!" ;
Scanner scanner = new Scanner(s);
System.out.println( "" + scanner.hasNext( "gopal" ));
System.out.println( "" + scanner.match());
System.out.println( "" + scanner.nextLine());
scanner.close();
}
catch (IllegalStateException e) {
System.out.println( "Exception caught is: " + e);
}
}
}
|
Output:
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()
Share your thoughts in the comments
Please Login to comment...