Scanner FindAll Streams MatchResult Tokens

Stream structured regex matches from a Scanner with findAll(Pattern), extracting capture groups and byte offsets from MatchResult lazily.

JavaData Fetching

Code

snippet
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

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.