Java Scanner match() Method

The match() method in Java, part of the java.util.Scanner class, returns a MatchResult object that provides information about the last match operation performed by the scanner.

Table of Contents

  1. Introduction
  2. match() Method Syntax
  3. Understanding match()
  4. Examples
    • Basic Usage
    • Extracting Match Information
  5. Real-World Use Case
  6. Conclusion

Introduction

The match() method returns a MatchResult object containing detailed information about the last matching operation performed by the Scanner. This is useful for extracting details such as the start and end positions of the match and the matched substring.

match() Method Syntax

The syntax for the match() method is as follows:

public MatchResult match()

Parameters:

  • This method does not take any parameters.

Returns:

  • A MatchResult object with information about the last match.

Throws:

  • IllegalStateException: If no match has been performed yet.

Understanding match()

The match() method is used after a successful scanning operation, such as hasNext() or next(), to retrieve the MatchResult of the last match. It provides detailed information about the match, including start and end positions and the matched string.

Examples

Basic Usage

To demonstrate the basic usage of match(), we will create a Scanner object and perform a matching operation, then retrieve the match details.

Example

import java.util.Scanner;
import java.util.regex.MatchResult;

public class MatchExample {
    public static void main(String[] args) {
        String input = "apple banana cherry";

        // Create Scanner object in try-with-resources to ensure it closes automatically
        try (Scanner scanner = new Scanner(input)) {
            while (scanner.hasNext()) {
                String token = scanner.next();
                System.out.println("Token: " + token);

                // Retrieve the match result
                MatchResult match = scanner.match();
                System.out.println("Match start: " + match.start());
                System.out.println("Match end: " + match.end());
            }
        } // Scanner is automatically closed here
    }
}

Output:

Token: apple
Match start: 0
Match end: 5
Token: banana
Match start: 6
Match end: 12
Token: cherry
Match start: 13
Match end: 19

Extracting Match Information

This example shows how to extract detailed match information using the match() method.

Example

import java.util.Scanner;
import java.util.regex.MatchResult;

public class ExtractMatchInfoExample {
    public static void main(String[] args) {
        String input = "apple123 banana456 cherry789";

        // Create Scanner object in try-with-resources to ensure it closes automatically
        try (Scanner scanner = new Scanner(input)) {
            while (scanner.hasNext("\\w+\\d+")) {
                String token = scanner.next();
                System.out.println("Token: " + token);

                // Retrieve the match result
                MatchResult match = scanner.match();
                System.out.println("Matched text: " + match.group());
                System.out.println("Match start: " + match.start());
                System.out.println("Match end: " + match.end());
            }
        } // Scanner is automatically closed here
    }
}

Output:

Token: apple123
Matched text: apple123
Match start: 0
Match end: 8
Token: banana456
Matched text: banana456
Match start: 9
Match end: 18
Token: cherry789
Matched text: cherry789
Match start: 19
Match end: 28

Real-World Use Case

Parsing Structured Text

In real-world applications, the match() method can be used to parse structured text, such as log files or formatted data, where extracting detailed match information is crucial.

Example

import java.util.Scanner;
import java.util.regex.MatchResult;

public class LogParser {
    public static void main(String[] args) {
        String log = "ERROR 2023-06-24: Connection lost\nINFO 2023-06-25: Connection restored";

        // Create Scanner object in try-with-resources to ensure it closes automatically
        try (Scanner scanner = new Scanner(log)) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                try (Scanner lineScanner = new Scanner(line)) {
                    if (lineScanner.hasNext("(ERROR|INFO)\\s\\d{4}-\\d{2}-\\d{2}:\\s.+")) {
                        String token = lineScanner.next();
                        MatchResult match = lineScanner.match();
                        System.out.println("Log entry: " + token);
                        System.out.println("Matched text: " + match.group());
                        System.out.println("Match start: " + match.start());
                        System.out.println("Match end: " + match.end());
                    }
                }
            }
        } // Scanner is automatically closed here
    }
}

Output:

Log entry: ERROR
Matched text: ERROR 2023-06-24: Connection lost
Match start: 0
Match end: 32
Log entry: INFO
Matched text: INFO 2023-06-25: Connection restored
Match start: 0
Match end: 34

Conclusion

The Scanner.match() method provides a way to retrieve detailed information about the last match operation performed by the Scanner. It is useful for extracting match details such as start and end positions and the matched substring. Always close the Scanner using try-with-resources to ensure proper resource management.

Comments