Java Scanner match() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.match() returns a java.util.regex.MatchResult describing the most recent successful match performed by the scanner—such as findInLine(), findWithinHorizon(), skip(), or next(pattern).

Through that MatchResult, you can read parenthesized capture groups with group(int) and inspect match boundaries with start() and end().

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.match(...).

Syntax

Import java.util.regex.MatchResult and call sc.match() right after a successful match.

Java
Scanner sc = new Scanner("Item SKU-805");
if (sc.findInLine("([A-Z]+)-(\\d+)") != null) {
    MatchResult m = sc.match();
    String prefix = m.group(1);   // "SKU"
    String code = m.group(2);     // "805"
}
CallWhat it does
sc.match().group()Returns the entire substring matched by the last operation.
sc.match().group(1)Returns the first parenthesized capture group.
sc.match().groupCount()Returns how many capturing groups the pattern defines.
sc.match().start() / end()Buffer start (inclusive) and end (exclusive) offsets of the match.

On streaming inputs such as large files or System.in, start() and end() report character offsets within the scanner's current internal buffer rather than absolute offsets from the start of the stream.

Library declarations
Java
// java.util.Scanner
public MatchResult match()

Parameters

ParameterDescription
Nonematch() takes no parameters.

Return Value

Return ValueDescription
MatchResultImmutable match result from the last successful match operation.
Throws IllegalStateExceptionIf no match has occurred yet, or if the last match attempt failed.

Compare with Similar Methods

Operations that populate match():

MethodHow it differs
findInLine(p)Populates match() when non-null; clears it on null.
findWithinHorizon(p, h)Cross-line match whose groups stay in match().
skip(p)Records the skipped prefix in match().
next(p)Captures token groups when pattern overload succeeds.

Java Examples

Example 1 — Extract Capture Groups from a Product Code

Match ([A-Z]+)-(\\d+) inside a line and pull out both parts cleanly using MatchResult.

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

public class ScannerMatchGroups {
    public static void main(String[] args) {
        String item = "Order SKU-805 qty 3";
        try (Scanner sc = new Scanner(item)) {
            if (sc.findInLine("([A-Z]+)-(\\d+)") != null) {
                MatchResult res = sc.match();
                System.out.println("Full match:  " + res.group());
                System.out.println("Group count: " + res.groupCount());
                System.out.println("Prefix (1):  " + res.group(1));
                System.out.println("Number (2):  " + res.group(2));
            }
        }
    }
}

How It Works

  1. Guard with non-null check. Checking findInLine(...) != null ensures a valid match exists before calling sc.match().
  2. Group 0 vs groups 1 and 2. group() gives "SKU-805" while group(1) and group(2) return "SKU" and "805".
  3. No extra Pattern/Matcher boilerplate. Scanner runs the regex internally and shares the MatchResult directly.

Example 2 — Inspect group(), start(), and end() After skip() and findWithinHorizon()

Track match positions on a short string after both skip() and findWithinHorizon().

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

public class ScannerMatchOffsets {
    public static void main(String[] args) {
        String text = "Key: 42\nVal: 99";
        try (Scanner sc = new Scanner(text)) {
            sc.skip("Key:\\s*");
            MatchResult m1 = sc.match();
            System.out.println("skip -> [" + m1.group() + "] start=" + m1.start() + ", end=" + m1.end());

            sc.findWithinHorizon("Val:\\s*(\\d+)", 0);
            MatchResult m2 = sc.match();
            System.out.println("horizon -> [" + m2.group(1) + "] start=" + m2.start() + ", end=" + m2.end());
        }
    }
}

How It Works

  1. Buffer offsets on short strings. Skipping "Key: " matches indices 0 (inclusive) through 5 (exclusive).
  2. Second match updates result. findWithinHorizon spans from index 8 (right after \n) through index 15.
  3. Capture inside horizon match. m2.group(1) isolates "99" even though m2.start()/end() cover the whole "Val: 99" match.

Example 3 — Catch IllegalStateException Before a Match and After a Failed Search

Demonstrate the two situations where calling sc.match() throws IllegalStateException.

Java
import java.util.Scanner;

public class ScannerMatchMissing {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("hello world")) {
            try {
                sc.match();
            } catch (IllegalStateException e) {
                System.out.println("Before any scan: " + e.getClass().getSimpleName());
            }
            sc.next("hello");
            System.out.println("After next(\"hello\"): " + sc.match().group());
            String miss = sc.findInLine("\\d+");
            System.out.println("Failed search returned: " + miss);
            try {
                sc.match();
            } catch (IllegalStateException e) {
                System.out.println("After failed findInLine: " + e.getClass().getSimpleName());
            }
        }
    }
}

How It Works

  1. No prior match yet. Calling match() immediately on a fresh scanner throws IllegalStateException.
  2. Pattern next() sets MatchResult. Calling sc.next("hello") records "hello" so match().group() succeeds.
  3. Failed search clears old match. Once findInLine("\\d+") returns null, the earlier "hello" match is invalidated and match() throws again.

Frequently Asked Questions

A java.util.regex.MatchResult representing the last successful match from findInLine, findWithinHorizon, skip, next, or hasNext.
Either no scanning/matching method has succeeded yet, or the most recent match attempt failed (e.g. findInLine returned null).
Start (inclusive) and end (exclusive) character positions inside the scanner buffer; on streaming inputs, buffer shifts change those numbers.
Call sc.match().group(1), sc.match().group(2), etc., after matching a regex with parentheses.
No. MatchResult is a read-only view of that match, though subsequent scanner operations can replace the scanner stored match.

Next: next()

Read and return the next complete token as a String.

next() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful