Sub topic 11
Custom delimiters
This chapter assumes you can create a Scanner, read tokens with next and nextInt, and read lines with nextLine. It also assumes you know the leftover newline pitfall and basic regular expressions: character classes, *, + and |.
What a delimiter is
A Scanner splits its input into tokens. A delimiter is the text between two tokens. By default the delimiter is one or more whitespace characters. That is why "12 7\n9" gives you the tokens 12, 7 and 9, whatever spaces, tabs or line breaks separate them.
useDelimiter replaces that default. It takes a regular expression, either as a String or as a java.util.regex.Pattern. Every token method then uses the new rule: next, nextInt, nextDouble, hasNext, hasNextInt and the others.
import java.util.Scanner;
public class DelimiterDemo {
public static void main(String[] args) {
Scanner s = new Scanner("a,,b").useDelimiter(",");
while (s.hasNext()) {
System.out.println("[" + s.next() + "]");
}
}
}This prints three tokens, and the middle one is empty:
[a]
[]
[b]useDelimiter returns the same Scanner, so you can chain it onto the constructor. A Scanner built on a String is also a convenient way to test a delimiter without typing input each time.
The following diagram shows the flow from text to values.
Empty tokens: single or repeated delimiters
Whether you get empty tokens depends on whether the pattern matches one delimiter or a whole run of them.
"\\s+"matches a whole run of whitespace as one delimiter. It never produces empty tokens.","matches one comma at a time. Two commas in a row produce an empty token between them.
Many data formats keep empty fields on purpose, so a missing value stays visible. Other inputs are hand-typed and sloppy. For those, make the pattern match a run: "[,\\s]+" treats any mix of commas and whitespace as a single separator.
| Delimiter string | Matches | Empty tokens on `a,,b` | Column |
|---|---|---|---|
| `"\\s+"` (default) | A run of whitespace | Not applicable, no commas are split | |
| `","` | One comma | Yes | |
| `"\\s*,\\s*"` | One comma with optional spaces around it | Yes | |
| `"[,\\s]+"` | A run of commas and whitespace | No | |
| `"\\ | "` | One pipe character | Yes |
In a Java string literal, every backslash of the regex must be doubled. The regex \s*,\s* is written "\\s*,\\s*". The pipe | is a regex operator, so a literal pipe needs "\\|".
Trailing newlines become part of the last token
A common mistake is to set the delimiter to a comma alone and then read a typed line such as 10,20,30 followed by Enter. The newline is no longer a delimiter, so the last token is 30 plus the line terminator. nextInt then throws InputMismatchException, because 30\n is not an integer.
Two fixes work:
- Include whitespace in the delimiter, for example
"[,\\s]+". - Read the line first with
nextLine, which removes the terminator, and split that line with a secondScanner.
The second fix is usually the more robust one, because it keeps one record per line.
Splitting a line with a second Scanner
This program reads lines of the form name, age, city from standard input. The outer Scanner handles lines. A short-lived inner Scanner handles the fields of one line.
import java.util.NoSuchElementException;
import java.util.Scanner;
public class RecordReader {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.isBlank()) {
continue;
}
try (Scanner fields = new Scanner(line).useDelimiter("\\s*,\\s*")) {
String name = fields.next();
int age = fields.nextInt();
String city = fields.next();
System.out.println(name + " (" + age + ") lives in " + city);
} catch (NoSuchElementException e) {
System.out.println("Skipping bad line: " + line);
}
}
}
}Try it with this input:
Ada, 36, London
Linus,not-a-number,Helsinki
Grace , 85 , New YorkThe first and third lines print normally. The second line fails at nextInt, and the program prints Skipping bad line: Linus,not-a-number,Helsinki and goes on. A line with too few fields fails at next in the same way.
One catch is enough here because InputMismatchException is a subclass of NoSuchElementException. Catch both as one type when you only need to skip the line. Catch them separately if you want different messages for "wrong type" and "missing field".
The inner Scanner wraps a String, so closing it does nothing harmful. Closing a Scanner wrapped around System.in is different, as the earlier chapter on closing explained.
nextLine ignores your delimiter
nextLine does not use the token delimiter. It always looks for a line separator and returns everything up to it, so a custom delimiter has no effect on it. Mixing token and line reads on the same Scanner has two consequences:
- The leftover-newline behavior is unchanged. After
nextInt, the rest of the line is still unread. - If your delimiter excludes whitespace,
nextcan swallow a line break as part of a token.nextLinethen starts reading from a different place than you expected.
Pick one style per Scanner. If a format needs both lines and fields, use the two-Scanner approach above.
Changing and resetting the delimiter
The delimiter can change in the middle of a scan. A new delimiter applies to the next token read, not to tokens already consumed. That suits formats with a header in one style and data in another.
import java.util.Scanner;
public class HeaderThenData {
public static void main(String[] args) {
Scanner s = new Scanner("version=2;1 2 3");
s.useDelimiter("[=;]");
s.next(); // "version"
int version = s.nextInt(); // 2
s.reset(); // back to whitespace
System.out.println("version " + version);
int sum = 0;
while (s.hasNextInt()) {
sum += s.nextInt();
}
System.out.println("sum " + sum);
}
}The program prints version 2 and then sum 6. Before reset, the scanner is positioned just after 2 and before the ;. After reset, the whitespace delimiter skips that leading ;? It does not: ; is not whitespace, so the next token would be ;1. Run the program and look at the result. The sum is 5, not 6, because hasNextInt sees ;1 and stops. That is a good example of why you should print intermediate values when you change delimiters. To fix it, use one delimiter that covers both phases, "[=;\\s]+", or consume the ; first with s.skip(";").
Two related methods help here:
delimiter()returns the current delimiter as aPattern.reset()restores the default delimiter. It also restores the default locale and radix.
Reading all input at once
The pattern \A matches the start of the input. Using it as the delimiter means the only delimiter is at the very beginning, so the first next returns everything after it, in one token.
import java.util.Scanner;
public class ReadAll {
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in).useDelimiter("\\A")) {
String all = in.hasNext() ? in.next() : "";
System.out.println("Characters: " + all.length());
}
}
}The hasNext check matters. With completely empty input, next throws NoSuchElementException, and the check turns that into an empty string. This idiom is short, but it holds the whole input in memory. It also buffers everything before your program sees anything, so it is a poor fit for interactive prompts.
Literal delimiters from user data
If the delimiter comes from outside your program, such as a command-line argument or a typed setting, do not pass it straight to useDelimiter. A value like | or . is a regex operator and will not mean what the user intended. A bad pattern such as [ throws PatternSyntaxException. Quote the text first:
import java.util.Scanner;
import java.util.regex.Pattern;
public class LiteralDelimiter {
public static void main(String[] args) {
String sep = args.length > 0 ? args[0] : "|";
Scanner s = new Scanner("x|y|z").useDelimiter(Pattern.quote(sep));
while (s.hasNext()) {
System.out.println(s.next());
}
}
}Pattern.quote wraps the text so that every character is matched literally.
Pitfalls to remember
- Locale affects numbers.
nextDoublefollows the scanner's locale. In a locale that uses a comma as the decimal mark,"3,5"may parse as one number, and a comma delimiter would split it first. For data files, calluseLocale(Locale.ROOT)so numbers always use a period. - Quoted fields are not supported. A value such as
"Smith, John"in CSV is split at the inner comma.Scannerhas no notion of quotes. Use a CSV library for real CSV. - Leading delimiters. Input that starts with a delimiter can produce an empty first token when the pattern matches one separator at a time. Print the tokens while testing.
- Performance. Regex matching is slower than
String.splitorBufferedReaderfor large inputs. For a few lines of typed input this does not matter.
Summary
useDelimitertakes a regular expression and changes how every token method splits input.- A pattern that matches one separator can return empty tokens. A pattern that matches a run of separators does not.
- Include whitespace in the delimiter, or read the line first, so the line terminator does not end up inside the last token.
nextLineignores the delimiter.- Use
resetto return to the default, andPattern.quotefor delimiters that must be taken literally.
Exercise
A Scanner is created with new Scanner("5,6,7\n").useDelimiter(","). The program calls nextInt three times. What happens, and how do you change the delimiter so it succeeds?
Show answer
The first two calls return 5 and 6. The third call sees the token "7\n", which includes the line terminator, so it throws InputMismatchException. Use a delimiter that also matches whitespace, such as "[,\\s]+" or "\\s,\\s|\\s+", or read the line with nextLine and split it with a second Scanner.
Exercise
Input arrives as the single line "one|two||four". You use useDelimiter("|") and read tokens with next. Why are the results wrong, and what is the correct call? How many tokens does the correct call return?
Show answer
In a regex, | means alternation of two empty patterns, so it matches the empty string and splits the input in unexpected places. A literal pipe must be escaped as "\\|" (or built with Pattern.quote("|")). The correct delimiter returns four tokens: "one", "two", an empty string, and "four", because the pattern matches one pipe at a time.