Java split(): How It Handles Delimiters and Limits

How-to basics · Updated November 22, 2026

In Java, String.split() divides a string wherever a regular-expression pattern matches and returns the pieces in a String[]. For example, "red,green,blue".split(",") returns three strings: red, green, and blue; the delimiter is not included in the returned pieces.

What String.split() does

split is an instance method on String, not a method that changes the original string. Java strings are immutable, so the method produces an array of strings and leaves the source string unchanged. Its most common form accepts one argument: a regular-expression pattern that marks where to cut.

The method is useful when input has a predictable separator, such as commas in a simple list, colons in a setting, or runs of whitespace between words. A basic example is:

String[] parts = "red,green,blue".split(",");

The array has three elements, with indexes 0 through 2. The separator itself is removed. If the pattern does not match anywhere in the input, the result is a one-element array containing the original string. This includes an empty input string: splitting "" on a comma gives one element whose value is the empty string.

The delimiter is a regular expression

The argument to split is interpreted as a Java regular expression, not automatically as a literal string. A comma is ordinary in regex syntax, so split(",") does what most readers expect. Other characters have special meanings. A period matches any character, while a vertical bar means alternation. Passing either one directly can therefore split in unexpected places.

To match a literal period, escape it for the regex and for the Java string literal: text.split("\."). To split on a literal vertical bar, use text.split("\|"). The two backslashes in Java source represent one backslash that is then interpreted by the regex engine. This double layer of escaping is a common source of confusion.

Regex patterns can also describe classes or repetitions rather than one exact character. For example, line.split("\s+") splits on one or more whitespace characters commonly used in text, such as spaces and tabs. The plus sign matters: it treats a run of spaces as a single delimiter instead of producing empty fields between adjacent spaces.

When a delimiter comes from a variable and must be treated literally, use Pattern.quote(delimiter) rather than trying to escape every possible regex character yourself. For example, text.split(Pattern.quote(separator)) is appropriate when separator might be a period, a pipe, or another regex operator. This requires importing java.util.regex.Pattern.

How the limit argument changes the result

The two-argument form, split(String regex, int limit), gives control over the number of splits and how empty pieces are handled. The limit is not simply a maximum number of separators; it controls the resulting array as follows:

  • Positive limit: Split at most limit - 1 times. The final array element contains whatever remains, including any further delimiters.
  • Zero limit: Split as many times as possible, then discard empty strings at the end of the array. This is what the one-argument form uses.
  • Negative limit: Split as many times as possible and preserve trailing empty strings.

For instance, with String input = "a,,b,";, input.split(",") returns ["a", "", "b"]. The empty element between the two adjacent commas remains, but the final empty element is discarded. By contrast, input.split(",", -1) returns ["a", "", "b", ""], preserving the fact that the input ended with a comma.

A positive limit is useful when only the first fields have a fixed structure. For the same input, input.split(",", 2) returns ["a", ",b,"]. It splits at the first comma only; the remaining text, including commas, is kept together in the last element. A limit of 1 means no split is performed and the result contains the whole input as one element.

There is a related edge case: when a delimiter matches at the very beginning, a positive-width match can produce an empty first element. A zero-width match at the beginning does not create that leading empty element. These rules are part of Java’s regex-based splitting behavior and can matter when using lookarounds or other patterns that match between characters.

Practical examples

For everyday code, the key is to select a pattern that represents the actual boundary in the data. Consider these examples:

  • Comma-separated values without quoted commas: String[] fields = row.split(",", -1); The negative limit preserves a blank final field, such as the last column in "Ada,42,".
  • Words separated by one or more spaces: String[] words = sentence.trim().split("\s+"); Trimming first avoids an empty first element if the sentence begins with spaces. For Java 11 and later, strip() can be used in place of trim() when Unicode-aware whitespace handling is wanted.
  • File name pieces separated by periods: String[] pieces = fileName.split("\."); The escaped period matches a literal dot. If the final extension or empty trailing portion matters, choose a suitable limit, often -1.
  • Split once at a colon: String[] pair = setting.split(":", 2); This keeps any additional colons in the second part, which is useful when the remainder should be treated as a value.

These are examples of string splitting, not complete data-format parsers. In particular, a comma-separated row containing quoted fields such as "Smith, Jane" cannot be reliably parsed by simply splitting on commas. The comma inside the quoted name is data, not a field boundary, and the basic pattern above does not understand CSV quoting rules.

Common surprises and mistakes

The most frequent bug is using a regex operator as if it were a literal delimiter. If a result looks as though it has split at every character, inspect the pattern for operators such as ., |, *, or brackets. Escape a literal operator or use Pattern.quote for a variable separator.

Another common surprise is the missing final field. The default zero limit drops trailing empty strings, so "name,age,".split(",") does not retain an empty third field. This is not the same as saying Java ignores all empty fields: interior empty fields are normally kept. If every field position matters, using a negative limit is often the right choice.

Whitespace deserves similar care. Splitting on a single space with split(" ") treats each space separately; repeated spaces can create empty elements. Splitting on "\s+" groups consecutive whitespace. However, a string that begins with whitespace may still yield an empty first element because the delimiter begins at the start. Trim or strip the input first only if removing leading and trailing whitespace is correct for the data.

Finally, an invalid regular expression causes a PatternSyntaxException at runtime. If a pattern is fixed, validate it during development. If it is assembled from user-provided text, quote literal components rather than inserting them directly into a regex.

When to use Pattern or another approach

For a one-off split, String.split is concise and readable. Internally, it uses Java’s regular-expression machinery. If the same regex is applied repeatedly, compile it once as a Pattern and reuse that pattern’s split method; this avoids repeatedly expressing and compiling the same pattern in application code. A Pattern can be shared, while a Matcher is the object used for operations that examine a particular input.

Other tools fit different jobs. StringTokenizer is an older option for simple tokenization, but it does not offer the same regex-based boundary behavior and typically does not preserve empty fields. Scanner can read tokens using a delimiter pattern and is useful when processing input progressively rather than turning the whole string into an array. For structured formats such as CSV, use a parser that implements the format’s quoting and escaping rules instead of relying on a simple split.

Choose based on what the input means: use split for a string with clear boundaries, a reusable Pattern for repeated regex work, a scanner for token-by-token reading, and a format-aware parser when delimiters can also appear inside quoted or escaped values.

Frequently Asked Questions

Does Java split include the delimiter in the result?
No. It uses the regex match as a boundary and returns the text between matches. If the delimiter itself must be retained, capture groups or a different parsing approach may be needed.

Why does split remove the last empty string?
The one-argument method behaves like split(regex, 0), and a zero limit discards trailing empty strings. Use a negative limit, such as split(",", -1), to retain them.

How do I split on a dot or pipe in Java?
Escape the character in the regex and Java literal: use split("\.") for a dot and split("\|") for a pipe. For a literal separator stored in a variable, pass Pattern.quote(separator).

How do I split on multiple spaces?
Use a pattern such as split("\s+"), which matches a run of whitespace characters. If leading whitespace should not create an empty first element, remove it first only when that matches the input requirements.

Can split parse a CSV file?
Not reliably when fields may contain quoted commas, escaped quotes, or line breaks. A simple split treats every matching comma as a boundary. Use a CSV parser for data that follows CSV rules.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.