Java split() Method: Split Strings with Regex and Limits

How-to basics · Updated November 22, 2026

To split a string in Java, call text.split(regex); for example, "red,green,blue".split(",") returns three pieces. The argument is a regular expression, not always a plain-text delimiter, so escape special characters such as a dot. Use split(regex, limit) when you need to keep trailing empty fields or control how many pieces are returned.

What You’ll Need

  • A Java development kit (JDK) and a place to write and run Java code, such as an IDE or a terminal.
  • A string to split and a clear idea of what separates its fields: a comma, whitespace, a symbol, or another pattern.
  • Basic familiarity with Java string literals and arrays. The examples use the standard String class and require no extra library.

Step-by-Step

  1. Choose the string and separator. Start by identifying the exact boundary between the pieces you want. For a comma-separated list, the text "red,green,blue" has commas between its three values. Java’s String.split method returns a String[] array, so decide whether an array is a suitable way to use the result. If you need to keep the original string, there is no special setup: split creates an array and does not alter the string.
  2. Call split with a regular expression. Put the delimiter pattern in the method call. A comma has no special meaning in regular expressions, so it can be passed directly. This complete example prints each piece:
    String text = "red,green,blue";
    String[] parts = text.split(",");
    
    for (String part : parts) {
        System.out.println(part);
    }

    The output is red, green, and blue, each on its own line. The method signature takes a regex, which is why some delimiters need extra care even though simple ones, such as a comma or colon, work as written.

  3. Use a regex when the separator varies. A regular expression can represent a group of possible separators or repeated whitespace. For example, "[,;]" matches either a comma or a semicolon, while "\\s+" matches one or more whitespace characters. In Java source, write the whitespace pattern as "\\s+": the Java string literal consumes one backslash, leaving \s+ for the regex engine. Example:
    String line = "Ada   Lin\t28";
    String[] fields = line.split("\\s+");

    Here, three spaces and the tab each count as part of a whitespace run, so the result contains Ada, Lin, and 28. If your input can start or end with whitespace, consider trimming it first or otherwise deciding how those boundary spaces should be handled; a delimiter at the start can produce a leading empty field.

  4. Escape regex metacharacters when you mean them literally. A dot in a regex means “any character,” not a period. In a Java string, escape the backslash as well, so use "\\." to split on literal periods:
    String version = "17.0.2";
    String[] numbers = version.split("\\.");

    The array contains 17, 0, and 2. Other regex metacharacters include |, *, +, ?, parentheses, brackets, and backslashes. If a separator is a variable containing arbitrary literal text, use Pattern.quote rather than trying to escape every possible character yourself:

    import java.util.regex.Pattern;
    
    String delimiter = "a+b";
    String[] pieces = "lefta+bright".split(Pattern.quote(delimiter));

    This treats the entire value of delimiter as ordinary text.

  5. Choose a limit if empty fields matter. The one-argument form behaves as though its limit were zero: it discards empty strings at the end of the result. That can hide meaningful blank fields. Pass a negative limit to retain trailing empties:
    String record = "name,age,,";
    String[] columns = record.split(",", -1);

    This returns four elements: name, age, an empty string, and another empty string. By contrast, record.split(",") drops the trailing empty elements. A positive limit controls the number of splits, not the maximum number of separators: for example, "id=42=extra".split("=", 2) returns id and 42=extra. The final array element contains the unsplit remainder.

  6. Check and use the resulting array. Print the elements or inspect parts.length while developing. Access an element with an index such as parts[0], remembering that Java arrays start at zero and that the number of pieces may differ from what you expect. If you need to process every item, a loop is safer than assuming a fixed number of fields. Also consider validating the field count before reading a particular position, especially when the string comes from a file, user input, or a network request.

Common Mistakes

  • Passing a special character without escaping it. Calling text.split(".") does not mean “split on periods”; the dot matches any character. Use "\\." for a literal dot. A bare pipe is also special: use "\\|" to split on the pipe character.
  • Forgetting that Java strings and regexes both use backslashes. The regex for a literal period is \., but the Java source code must represent that backslash as "\\.". If the compiler reports an illegal escape, check the Java string literal. If the program compiles but splits incorrectly, check the regex meaning too.
  • Dropping trailing empty fields unintentionally. The default call removes empty strings at the end of the array. For records where blank final columns matter, use a negative limit, typically split(delimiter, -1).
  • Assuming split understands quoted CSV data. Splitting "red,\"dark, red\",blue" on commas also splits inside the quoted value. split is not a CSV parser. Use a CSV library when the input follows CSV quoting and escaping rules.
  • Assuming the delimiter will always match. When no delimiter matches, the result is a one-element array containing the original string. Do not assume a successful split guarantees multiple fields.

Tips

  • Use the simplest correct pattern. A literal comma needs only ","; use a regex character class such as "[,;]" only when either separator should count.
  • For general whitespace, "\\s+" collapses a run into one boundary. If you need to preserve repeated spaces as meaningful empty fields, do not use that pattern; define a delimiter that matches the data format instead.
  • Use split(regex, -1) for fixed-column records where blank final values must survive. Then validate the resulting array length before accessing expected columns.
  • If the same complex regex is used many times, compile it once with Pattern.compile and use the pattern’s split method. This can make the intent clearer and avoid repeatedly compiling the expression.
  • Test representative boundary cases: an ordinary input, adjacent delimiters, a delimiter at the end, no delimiter, and an empty field. These cases reveal most surprises in how the resulting array is shaped.

Troubleshooting

The string seems to split at every character. Check whether the pattern is a metacharacter such as . or |. Escape it for the regex, and then escape the backslash for the Java string literal. For example, use "\\." for a period.

Some expected columns are missing. Look for empty fields at the end of the input. The one-argument method discards trailing empty strings; retry with a negative limit, such as split(",", -1). Also inspect the input for extra or missing separators instead of trusting that every record has the same shape.

The result has only one element. Confirm that the pattern actually matches the separator in the input. A comma pattern will not match a semicolon, and a literal separator may differ because of spaces or capitalization. Print the original string and examine the exact characters; tabs and other whitespace can be hard to see.

The program throws an index error after splitting. An expression such as parts[2] fails if the array has fewer than three elements. Check parts.length first, and decide how to handle malformed or incomplete input. If whitespace at the beginning creates an unexpected empty element, trim the input when that is appropriate for your data, or adjust the regex to match the intended format.

Frequently Asked Questions

Does Java split take a string or a regex?
It takes a regular expression. Simple delimiters such as commas can be passed directly, but regex metacharacters need escaping when you want their literal meaning.

How do I split a string on whitespace?
Use text.split("\\s+") to treat one or more whitespace characters as a separator. If leading or trailing whitespace is possible, decide whether to trim it before splitting.

How can I keep empty fields at the end?
Use a negative limit, for example text.split(",", -1). The default one-argument form removes trailing empty strings.

How do I split on a pipe or a dot?
Escape the regex character and its backslash in the Java literal: use "\\|" for a pipe and "\\." for a dot.

Does split change the original string?
No. Java strings are immutable, and split returns a new array of strings. The original value remains unchanged.

Can I use split to read CSV files?
Not reliably when fields can contain quoted commas, quotes, or escaped line breaks. Use a CSV parser that follows the file’s format rather than splitting on commas alone.

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.