Practical technical guides / Core IT: Java

Java String.split Drops Trailing Empty Fields and Reads Its Argument as a Regex

Measured on JDK 23: split drops trailing empty fields unless the limit is negative, and a pipe or dot argument is a regex. How to parse delimited records safely.

By Sandeep Belgavi · Published 2026-11-05

Measured on JDK 23: split drops trailing empty fields unless the limit is negative, and a pipe or dot argument is a regex. How to parse delimited records safely.

A return record that lost two fields

Tanishka's import job reads daily return records for Belgavi's Book Store from a partner's flat file. Each line has five comma-separated fields: case id, customer, action, refund amount and a note. When the refund amount and note are empty, the line ends in two commas: CASE-1042,Jenya,refund,,. The job splits each line with line.split(","), reads fields[3], and fails with ArrayIndexOutOfBoundsException on exactly those lines. The array has three elements, not five.

That is documented behaviour of String.split, not a bug, and it is one of two surprises in the method. The other is that its argument is a regular expression, so split("|") and split(".") do something very different from splitting on a pipe or a dot. This guide measures both on JDK 23 and shows how to split delimited data predictably. Every result below was printed by the companion probe on Java 23.0.2.

What split returns, measured

ExpressionLengthResult
"CASE-1042,Jenya,refund,,".split(",")3["CASE-1042", "Jenya", "refund"]
"CASE-1042,Jenya,refund,,".split(",", -1)5["CASE-1042", "Jenya", "refund", "", ""]
"CASE-1042,Jenya,refund,,".split(",", 3)3["CASE-1042", "Jenya", "refund,,"]
",,,".split(",")0[]
"".split(",")1[""]
",a".split(",")2["", "a"]
"a,,b".split(",")3["a", "", "b"]
" a b".split(" +")3["", "a", "b"]

Why trailing empty strings disappear

split(regex) is defined as split(regex, 0), and the Javadoc for the two-argument form explains the limit parameter:

  • If the limit is positive, the pattern is applied at most limit minus one times, the array's length is no greater than the limit, and the last element contains all input beyond the last matched delimiter. That is why split(",", 3) keeps "refund,," as its third element.
  • If the limit is zero, the pattern is applied as many times as possible, the array can have any length, and "trailing empty strings will be discarded". That is the default, and it is why the record lost its last two fields, and why ",,,".split(",") returns an empty array.
  • If the limit is negative, the pattern is applied as many times as possible and the array can have any length. Nothing is discarded.

Leading empty strings are different: they are kept. ",a".split(",") returns ["", "a"]. The Javadoc adds one subtlety: "A zero-width match at the beginning however never produces such empty leading substring." So "abc".split("") returns three elements, a, b and c, with no empty first element.

And the empty input is a special case of its own: when the pattern does not match, the result is an array containing the input, so "".split(",") has length 1, not 0. A loop that treats "no fields" as length == 0 will see one empty field.

For delimited records, the rule is simple: always pass a negative limit.

String[] fields = line.split(",", -1);
if (fields.length != 5) {
    throw new IllegalArgumentException("expected 5 fields, got " + fields.length + ": " + line);
}

Checking the length explicitly turns a malformed line into a clear error at the point of parsing, instead of an index exception or, worse, a silently shifted field somewhere later.

The argument is a regular expression

String.split takes a regex. Many delimiters are regex metacharacters, and the probe shows what happens when they are passed unescaped:

"CASE-1042|Jenya|refund".split("|");     // length 22: an empty alternation matches between every character
"CASE-1042|Jenya|refund".split("\\|");   // length 3: the escaped pipe is a literal pipe
"978.0.13.468599.1".split(".");          // length 0: "." matches every character, every piece is empty
"978.0.13.468599.1".split("\\.");        // length 5: the escaped dot is a literal dot

The dot case is the nastier one: it does not fail, it returns an empty array, and code that loops over the result simply does nothing.

The robust way to split on a literal string is Pattern.quote, which wraps it so no character is special:

import java.util.regex.Pattern;

private static final Pattern PIPE = Pattern.compile(Pattern.quote("|"));

String[] fields = PIPE.split(line, -1);   // literal pipe, keep trailing empty fields

Compiling the pattern once also avoids recompiling it for every line. The JDK source of String.split has a fast path that skips regex compilation for a single character that is not a metacharacter, or a backslash followed by a single non-alphanumeric character, but a precompiled Pattern is fast for every delimiter and states the intent plainly. Pattern.split(input, limit) follows the same limit rules as String.split; the probe confirmed that Pattern.compile(",").split(row, -1) also returns five fields.

Two more methods worth knowing

  • Pattern.splitAsStream(input) behaves like a limit of zero: for the five-field record it produced three elements. There is no limit parameter, so it is the wrong tool when trailing empty fields matter.
  • String.splitWithDelimiters(regex, limit), added in JDK 21, returns the delimiters too. For the record with limit -1 it returned nine elements, the five fields and the four commas. It is useful for tokenisers that need to preserve the original text.

Other splitters disagree too

Java has older tokenising classes, and they do not agree with split or with each other. The probe ran the same five-field record through two of them:

MethodTokens for CASE-1042,Jenya,refund,,What happened to the empty fields
split(",", -1)5both kept
split(",")3both dropped as trailing
new StringTokenizer(row, ",")3never returned: consecutive delimiters count as one
new Scanner(row).useDelimiter(",")4the empty field between the two commas kept, the final one not

StringTokenizer also collapsed an empty field in the middle: CASE-1042,,refund gave two tokens, so the customer field vanished and the action moved into its place. Its Javadoc describes it as a legacy class kept for compatibility and recommends split or the java.util.regex package instead. The lesson for code review is that "split this line into fields" has at least four meanings in the standard library, and only split with a negative limit, or Pattern.split with one, keeps every field.

A parser for the return records

Putting the rules together, a parser for the partner's file checks each assumption explicitly and reports the line it rejects:

import java.util.regex.Pattern;

record ReturnRecord(String caseId, String customer, String action, Long refundCents, String note) {
    private static final Pattern COMMA = Pattern.compile(Pattern.quote(","));

    static ReturnRecord parse(String line) {
        String[] f = COMMA.split(line, -1);
        if (f.length != 5) throw new IllegalArgumentException("expected 5 fields, got " + f.length + ": " + line);
        if (!f[0].startsWith("CASE-")) throw new IllegalArgumentException("bad case id: " + line);
        Long cents = f[3].isEmpty() ? null : Long.valueOf(f[3]);
        return new ReturnRecord(f[0], f[1], f[2], cents, f[4]);
    }
}

The companion example's tests feed it a complete line, a line ending in two empty fields, a line with four fields and an empty line, and assert the result or the error message for each. The empty line fails with "expected 5 fields, got 1", which is the "".split(",") rule from the first table showing up in practice.

When split is the wrong tool

Splitting on a comma is correct only if the field values can never contain a comma. A customer note such as "cover torn, pages fine" in a real CSV file is quoted, and RFC 4180 defines how fields containing commas, quotes or line breaks are enclosed in double quotes, with embedded quotes doubled. split(",", -1) breaks such a field in two. If the input is CSV produced by a spreadsheet or another system, use a CSV parser that implements those rules, and keep split for formats you control and know contain no quoting: log lines with a fixed delimiter, keys like CASE-1042:refund:damaged-cover, or tab-separated output of your own tools.

Finding the bug in existing code

The problem is easy to search for. Look for calls to split( with one argument whose result is indexed or whose length is compared with a fixed number of fields, and for split arguments that are single metacharacters: "|", ".", "$", "^", "*", "+", "?", "(", ")", "[", "{" or "\\". Static analysis tools flag some of these; SpotBugs, for example, has a check for a dot or a pipe used as a regular expression. A short unit test per parser with a line ending in empty fields, an empty line and a line with the delimiter inside a value catches the rest.

Limits

The table comes from one JDK, 23.0.2, but the behaviour is specified in the String and Pattern Javadoc and has been stable for many releases; splitWithDelimiters needs JDK 21 or later. The records are synthetic.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/java/string_split_edges. Views are my own and do not represent any employer, past or present.