Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java String.split limit: retain trailing empty fields in records

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

String.split(regex, -1) preserves trailing empty fields that the default split call discards.

Preserve the record width

A delimited import line may end with an empty optional note. If a parser discards that final field, a schema-width check can accept or reject the wrong record. A negative split limit keeps the final empty string; a positive limit can instead cap the number of pieces when the final field may contain delimiters.

The delimiter is a regex. A literal pipe must be quoted or escaped; quoting user text covers a delimiter supplied at runtime. The existing trailing-fields lesson introduces this issue; this page adds an explicit schema-width gate and a bounded split contract.

Limit allocations

Splitting an entire untrusted line creates an array and substrings. Cap line length and expected field count first. If a field can contain escaped delimiters or quoted text, a plain split call is the wrong parser.

Working program

Java
import java.util.Arrays;
import java.util.regex.Pattern;

public class ManifestFieldWidth {
    public static void main(String[] args) {
        String manifestLine = "R-47|ready|";
        String separator = Pattern.quote("|");
        String[] defaultFields = manifestLine.split(separator);
        String[] preservedFields = manifestLine.split(separator, -1);
        System.out.println("default=" + defaultFields.length);
        System.out.println("preserved=" + Arrays.toString(preservedFields));
        String[] bounded = "R-47|ready|note|with|pipes".split(separator, 3);
        System.out.println("bounded=" + Arrays.toString(bounded));
    }
}

Output

Output
default=2
preserved=[R-47, ready, ]
bounded=[R-47, ready, note|with|pipes]

Cost and ownership

Split scans the input and allocates an array plus result strings. A positive limit bounds the number of pieces, not the input length or final piece size. Validate both record length and schema before storing the fields.

Common Mistakes

  • Do not use the default split call when trailing blanks are meaningful.
  • Do not assume the separator argument is literal text.
  • Do not use split to parse a quoted CSV-style format.

Read next

Java String.split: preserve empty trailing fields in a record, Java Pattern.quote: match a supplied token literally, Java bounded line reader: reject oversized records without buffering the file, Java strings and content equality.

java
regex
regex-split-limit
Storage details