Home Java Scanner Methods match() Java Scanner match() Method 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.
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"
} Call What 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.util.Scanner
public MatchResult match() Parameters Parameter Description None match() takes no parameters.
Return Value Return Value Description MatchResultImmutable match result from the last successful match operation. Throws IllegalStateException If no match has occurred yet, or if the last match attempt failed.
Important
Calling match() before any match operation, or right after a failed findInLine()/findWithinHorizon() (returning null) or failed hasNext(pattern), throws IllegalStateException. Always check that your match call returned non-null before calling sc.match().
Compare with Similar Methods Operations that populate match():
Method How 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 1. Capture groups 2. Start and end offsets 3. IllegalStateException cases Example 1 — Extract Capture Groups from a Product Code Match ([A-Z]+)-(\\d+) inside a line and pull out both parts cleanly using MatchResult.
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));
}
}
}
} Full match: SKU-805
Group count: 2
Prefix (1): SKU
Number (2): 805 How It Works Guard with non-null check. Checking findInLine(...) != null ensures a valid match exists before calling sc.match().Group 0 vs groups 1 and 2. group() gives "SKU-805" while group(1) and group(2) return "SKU" and "805".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().
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());
}
}
} skip -> [Key: ] start=0, end=5
horizon -> [99] start=8, end=15 How It Works Buffer offsets on short strings. Skipping "Key: " matches indices 0 (inclusive) through 5 (exclusive).Second match updates result. findWithinHorizon spans from index 8 (right after \n) through index 15.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.
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());
}
}
}
} Before any scan: IllegalStateException
After next("hello"): hello
Failed search returned: null
After failed findInLine: IllegalStateException How It Works No prior match yet. Calling match() immediately on a fresh scanner throws IllegalStateException.Pattern next() sets MatchResult. Calling sc.next("hello") records "hello" so match().group() succeeds.Failed search clears old match. Once findInLine("\\d+") returns null, the earlier "hello" match is invalidated and match() throws again.Frequently Asked Questions What does Scanner.match() return? A java.util.regex.MatchResult representing the last successful match from findInLine, findWithinHorizon, skip, next, or hasNext.
Why does Scanner.match() throw IllegalStateException? Either no scanning/matching method has succeeded yet, or the most recent match attempt failed (e.g. findInLine returned null).
What do match().start() and match().end() return? Start (inclusive) and end (exclusive) character positions inside the scanner buffer; on streaming inputs, buffer shifts change those numbers.
How do I read capture groups with Scanner? Call sc.match().group(1), sc.match().group(2), etc., after matching a regex with parentheses.
Is the MatchResult returned by match() mutable? No. MatchResult is a read-only view of that match, though subsequent scanner operations can replace the scanner stored match.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion