Java String split(): Syntax, Regex, and Examples

How-to basics · Updated November 22, 2026

In Java, call String.split(regex) to divide a string wherever a regular expression matches; it returns the pieces in a String[]. For example, "red,green,blue".split(",") returns ["red", "green", "blue"]. The important detail is that the argument is a regular expression, not necessarily a literal delimiter.

What String.split does

split finds matches for a separator pattern and uses those matches as boundaries between substrings. It does not include the matched separators in the returned pieces. The original string is not changed: Java strings are immutable, and the method creates and returns an array of strings.

The method has two commonly used forms:

  • String[] parts = text.split(regex);
  • String[] parts = text.split(regex, limit);

The one-argument form behaves like the two-argument form with a limit of zero. This limit controls how many times splitting occurs and, importantly, whether empty pieces at the end are kept. A frequent source of bugs is assuming that the separator argument is always treated as ordinary text.

Basic syntax and a simple example

For a delimiter that has no special meaning in regular expressions, the call is straightforward. A comma, for example, is not a regex operator:

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

The array has three elements: "red", "green", and "blue". You can access them by index, starting at zero, or loop over the array:

for (String color : colors) {
    System.out.println(color);
}

Use the overload with a limit when you want to control how many pieces are produced. For instance, splitting "name:description:extra" with split(":", 2) produces ["name", "description:extra"]. This is useful when the first separator has a special role but the rest of the text should stay together.

Why the separator is a regular expression

The argument to split is a regex, so some characters have special meanings. A period means “any character” in a regular expression, not a literal dot. Consequently, "file.txt".split(".") does not reliably split at the period; the pattern can match the characters themselves.

Escape a regex metacharacter to make it literal. In a Java string literal, the backslash must also be escaped, so a literal period is written as "\.":

String[] nameAndExtension = "file.txt".split("\.");
// ["file", "txt"]

For a delimiter supplied as a variable, escaping it manually is easy to get wrong. Use Pattern.quote to treat the whole value as literal text:

String delimiter = ".*";
String[] parts = text.split(Pattern.quote(delimiter));

This requires import java.util.regex.Pattern;. It is especially helpful when delimiters can contain characters such as ., |, ?, *, or brackets. If you want to split on any one of several characters, a character class can express that: text.split("[,:;]") separates at a comma, colon, or semicolon.

Understanding the limit argument and empty results

The limit determines the number of times the pattern is applied and how trailing empty strings are handled. The three cases are worth remembering:

  • A positive limit stops after at most limit - 1 matches. The final array element contains the remaining text, which may itself contain the separator.
  • A zero limit allows splitting without a fixed maximum, then removes empty strings at the end of the result. This is the default for split(regex).
  • A negative limit allows splitting without a fixed maximum and retains trailing empty strings.

For example, "a,,b,".split(",") returns ["a", "", "b"]: the empty field between the two commas remains, but the empty field after the final comma is discarded. If the final empty field matters, use "a,,b,".split(",", -1), which returns ["a", "", "b", ""].

A positive limit is useful for parsing a record whose last field may contain the delimiter. With "one:two:three".split(":", 2), the result is ["one", "two:three"]. With a limit of one, there is no split, so the result contains the original string as its only element. These details matter when empty fields represent real data, such as a missing final value in a delimited record.

Splitting on whitespace and other patterns

To split on one or more whitespace characters, use \s+ as the regex. The plus sign means “one or more,” so a run of spaces acts as a single separator rather than creating a series of empty fields:

String[] words = text.trim().split("\s+");

Be aware that whitespace at the start of the string can create an empty first element, because the separator matches at the beginning. The example trims first to avoid that common case. On Java 11 and later, strip() can be used instead of trim() when Unicode-aware whitespace trimming is desired. The meaning of regex whitespace can also depend on regex flags and Unicode settings, so applications processing international text should check the exact requirements rather than assume every visible spacing character is treated identically.

Regex patterns can describe more than one simple separator. For example, text.split("[,;]+") splits at one or more commas or semicolons. A pattern such as "\\s+" in source code represents the regex \s+, because Java string syntax processes backslashes before the regex engine sees them. When a pattern looks unexpectedly ineffective, check both layers of escaping: Java string literals first, regular-expression syntax second.

Common problems and practical checks

Several small checks prevent many splitting errors:

  • Check the regex meaning. Characters such as ., |, *, +, ?, parentheses, and brackets can act as regex syntax. Escape a literal metacharacter or quote a variable delimiter.
  • Decide what empty fields mean. Use a negative limit when trailing empty fields must be preserved; do not assume the default keeps them.
  • Check the input shape. If a line may be blank, missing, or malformed, validate it before accessing a particular array index.
  • Remember that array indexes start at zero. A two-part split has indexes zero and one, not one and two.
  • Consider whether a regex match exists. If the pattern does not match the input, the result is a one-element array containing the original input.

For example, "onlyone".split(",") does not return an empty array; it returns ["onlyone"]. Code that expects two fields should check parts.length before reading parts[1], and should report or handle an invalid record instead of assuming every input is well-formed.

Also note that split is not a complete CSV parser. A simple comma split cannot correctly handle quoted CSV fields such as "Smith, Jane", because it sees the comma inside the quotes as another separator. For real CSV data, use a CSV library that follows the relevant CSV format rather than trying to handle quoting, escaped quotes, and line breaks with a simple split pattern.

When to use Pattern or another approach

For a one-off split, String.split is concise and readable. If the same complex pattern is applied repeatedly, compile it once as a Pattern and call its split method:

Pattern separator = Pattern.compile("[,;]+");
String[] parts = separator.split(text);

This makes the reuse explicit and avoids expressing the same pattern repeatedly in the code. You can also provide a limit to Pattern.split. Choose based on clarity first; for a short input processed once, the direct string method is usually easier to read.

Other approaches suit different jobs. StringTokenizer is an older utility for tokenizing strings, but it does not offer the same regex-based delimiter rules and is generally less flexible for new parsing code. If the task is to locate one delimiter or keep just the text before or after it, methods such as indexOf and substring can make the intended operation explicit. If the format has quoting, nesting, or escaping rules, use a parser designed for that format rather than a plain split.

Frequently Asked Questions

Does Java split remove the delimiter?

Yes. The matched delimiter marks where the pieces are separated and is not included in the returned strings. If you need to retain separators, use a different parsing approach or a regex with capturing groups and verify the resulting behavior for your pattern.

How do I split a string by a dot in Java?

Use text.split("\\.") in Java source. The doubled backslash creates a single backslash for the regex engine, which then treats the dot literally. For a delimiter stored in a variable, use Pattern.quote(delimiter).

How do I keep empty strings at the end?

Pass a negative limit, usually -1: text.split(",", -1). The default one-argument form uses a zero limit and discards trailing empty strings, though empty fields between delimiters are retained.

What does split return if the delimiter is not found?

It returns a one-element String[] containing the original input. Check the array length before assuming that a separator was present or that a later field exists.

Can split parse CSV files correctly?

Not in general. A comma may occur inside a quoted field, and CSV also has rules for quotes and line breaks. Use a CSV parser for CSV data; split(",") is suitable only for a simpler format where commas never need escaping or quoting.

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.