Scanner Delimiter Token Parsing

Point Scanner at any string or stream, swap its delimiter for a regex, and pull typed tokens with nextInt, which throws on non-numeric input.

JavaCli Tooling

Code

snippet
import java.util.Scanner;

public class ConfigReader {

    public static void main(String[] args) {
        String line = "deploy=prod replicas=3 region=us-east-1";

        // 默认分隔符是空白;useDelimiter 换成任意正则,token parsing 逐段推进
        Scanner scanner = new Scanner(line).useDelimiter("[= ]");
        while (scanner.hasNext()) {
            System.out.println("token: " + scanner.next());
        }

        // nextInt 直接读数值:非数字抛 InputMismatchException,而不是返回 0
        Scanner numbers = new Scanner("8080 abc 443").useDelimiter(" ");
        int port = numbers.nextInt();
        System.out.println("port: " + port);
        try {
            numbers.nextInt();
        } catch (java.util.InputMismatchException bad) {
            System.out.println("rejected: " + bad.getClass().getSimpleName());
        }

        scanner.close();
        numbers.close();
    }
}

How the snippet works

Scanner Delimiter Token Parsing reduces to the class ConfigReader and the function main.

Iteration happens inside while (scanner.hasNext()) — everything outside it runs once.

Applying it

Output lines are prefixed (token:, port:, rejected:), making each step’s effect easy to spot.

Statements that matter

Scanner numbers = new Scanner("8080 abc 443").useDelimiter(" ");
Scanner scanner = new Scanner(line).useDelimiter("[= ]");
String line = "deploy=prod replicas=3 region=us-east-1";

Interactive Tools for This Topic

FAQ

What does Scanner Delimiter Token Parsing print when run?
Running the file directly is enough — expect labeled output lines such as `token:`, `port:`, `rejected:`.