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.
Code
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
CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.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.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.