Scanner FindAll Streams MatchResult Tokens
Stream structured regex matches from a Scanner with findAll(Pattern), extracting capture groups and byte offsets from MatchResult lazily.
Code
import java.util.List;
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
public class ScannerMatchStream {
public static void main(String[] args) {
String log = "job=a1 status=200; job=b2 status=503; job=c3 status=500; job=d4 status=204";
Pattern entry = Pattern.compile("job=(\\w+)\\s+status=(\\d{3})");
try (Scanner scanner = new Scanner(log)) {
List<String> failures = scanner.findAll(entry)
.filter(mr -> Integer.parseInt(mr.group(2)) >= 500)
.map(mr -> mr.group(1) + "@" + mr.start() + ".." + mr.end() + "=" + mr.group(2))
.toList();
System.out.println("server errors: " + failures);
}
try (Scanner counter = new Scanner(log)) {
List<String> jobs = counter.findAll(entry)
.map(MatchResult::group)
.limit(2)
.toList();
System.out.println("first two hits: " + jobs);
}
}
}Walkthrough notes — Scanner FindAll Streams MatchResult Tokens
Scanner FindAll Streams MatchResult Tokens reduces to the class ScannerMatchStream and the function main.
try-with-resources closes each declared resource automatically on every exit path.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Signature: public static void main(String[] args)
The run emits 2 labeled sections — server errors:, first two hits: — one per step.
Key statements
.map(mr -> mr.group(1) + "@" + mr.start() + ".." + mr.end() + "=" + mr.group(2))
.toList();
.map(MatchResult::group)
.limit(2)
.toList();
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
FAQ
- What does Scanner FindAll Streams MatchResult Tokens print when run?
- No setup needed: run the file and look for labeled lines like `server errors:`, `first two hits:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.