Java Utility Library

Java Scanner - match() Method



The java.util.Scanner.match() method returns the match result of the last scanning operation performed by this scanner. This method throws IllegalStateException if no match has been performed, or if the last match was not successful.

Syntax

public MatchResult match()

Parameters

No parameter is required.

Return Value

Returns a match result for the last match operation.

Exception

Throws IllegalStateException - If no match result is available.

Example:

In the example below, the java.util.Scanner.match() method is used to check if there is any match thrown by the Scanner's underlying Readable.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello World 10 + 20 = 30.0";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    //print the next token matches the pattern
    System.out.println(MyScan.hasNext("..llo"));

    //find the last match and print it
    System.out.println(MyScan.match());

    //print the line
    System.out.println(MyScan.nextLine());

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

true
java.util.regex.Matcher$ImmutableMatchResult@65ab7765
Hello World 10 + 20 = 30.0

❮ Java.util - Scanner