java.util.Scanner match()

Description :

This java tutorial shows how to use the match() method of Scanner class of java.util package. This method returns a MatchResult object which corresponds to the result of the last operation by the scanner object.

Method Syntax :

public MatchResult match()

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

This method simply returns the match result of the last operation performed by the Scanner object.

Compatibility Version :

Requires Java 1.5 and up

Exception :

IllegalStateException

– The IllegalStateException will be thrown by calling the match() method if no match result is available from the last operation such as calling the method nextInt().

Discussion :

The Scanner match() method is helpful in getting useful information in pattern matching. It will give us access to the methods of return type MatchResult which will help us in debugging or can server as flag if we want to proceed further on our pattern matching.

Java Code Example :

This java example source code demonstrates the use of match() method of Scanner class. We have made use of the return type MatchResult to print which index the pattern match has been found.

package com.teknoscope.java.tutorial.scanner;

import java.util.Scanner;

/*
 * This is an example source code that shows the usage of match()
 * method to print useful information which concerns the pattern matching
 * of Scanner object
 */

public class ScannerMatchDemo {

	public static void main(String[] args) {

		// Initialize Scanner object
		Scanner scan = new Scanner("A E 4 1 3");
		// Printing the delimiter used
		System.out.println("Delimiter:"+scan.delimiter());
		scan.useRadix(16);
		// Print the radix the Scanner object is using
		System.out.println("Radix:"+scan.radix());
		// Printing the tokenized Strings
		while(scan.hasNextInt()){
			scan.nextInt();
			// printing the index where the delimiter has been found
			System.out.println("Pattern match at index:"+scan.match().start());
		}

		// closing the scanner stream
		scan.close();

	}

}

Sample Output :

Running the match() method example source code of Scanner class will give you the following output:

Delimiter:p{javaWhitespace}+
Radix:16
Pattern match at index:0
Pattern match at index:2
Pattern match at index:4
Pattern match at index:6
Pattern match at index:8

Exception Scenario :

Exception in thread "main" java.lang.IllegalStateException: No match result available
	at java.util.Scanner.match(Unknown Source)
	at com.teknoscope.java.tutorial.scanner.ScannerMatchDemo.main(ScannerMatchDemo.java:23)

Similar Method :

  • N/A

Suggested Reading List :

References :