Java’s split function is the String.split() method: it divides a string into an array of substrings using a regular expression as the separator. For example, "red,green,blue".split(",") returns three strings; the main detail to remember is that the separator is a regex, not always a literal character.
What Java’s split function does
split() belongs to Java’s String class and returns a String[]. It searches the original string for matches to a separator pattern, then puts the text between those matches into the result array. The matched separators are not included in the returned pieces.
This makes it useful for simple delimited text, such as a list of names separated by commas, a path separated by slashes, or a line divided on whitespace. It does not change the original string: Java strings are immutable, and the method creates a result containing the separated text.
The method has two commonly used forms:
split(String regex)splits using the regular expression and behaves as if its limit were zero.split(String regex, int limit)also takes a limit that controls how many pieces are returned and whether trailing empty pieces remain.
Syntax and a basic example
The argument is a regex written as a Java string. For a simple comma delimiter, the comma has no special meaning in Java regular expressions, so it can be passed directly. Assign the result to a string array and access each part by index, just as with any other array.
String names = "Mina,Leo,Sam";
String[] parts = names.split(",");
System.out.println(parts.length); // 3
System.out.println(parts[0]); // Mina
System.out.println(parts[1]); // Leo
System.out.println(parts[2]); // Sam
Array indexes start at zero, so the first element is parts[0]. If the number of fields is not known beforehand, iterate over the array rather than assuming a particular length:
for (String part : names.split(",")) {
System.out.println(part);
}
If a string contains no match for the separator, the result contains the original string as its single element. For instance, splitting "Mina" on a comma does not produce an empty array; it produces an array containing "Mina".
Why the separator is a regular expression
Java interprets the separator argument as a regular expression. Some characters have special regex meanings, so using one directly may split on something broader or different than intended. A period, for example, matches any character in a regex. Therefore text.split(".") does not mean “split at periods.”
To match a literal period, escape it for the regex and also escape the backslash for the Java string literal. That is why the Java source uses two backslashes:
String[] parts = "report.final.pdf".split("\\.");
// [report, final, pdf]
Other regex metacharacters that often surprise people include |, *, +, ?, parentheses, brackets, and backslashes. A literal pipe can be written as "\\|" in Java source. If the delimiter is supplied at runtime or may contain arbitrary characters, quoting it is safer:
import java.util.regex.Pattern;
String delimiter = ".";
String[] parts = text.split(Pattern.quote(delimiter));
Pattern.quote() turns the supplied text into a regex that matches it literally. This avoids writing custom escaping logic when a user-selected delimiter could be a regex metacharacter.
Controlling results with the limit argument
The second argument to split() changes both the maximum number of resulting pieces and how trailing empty strings are handled. This is one of the most important differences between the two overloads.
- A positive limit allows at most that many pieces. Once the limit is reached, any remaining text stays together in the final piece.
- A zero limit removes trailing empty strings from the result. This is what the one-argument
split(regex)form does. - A negative limit keeps trailing empty strings and allows all matches to split the input.
For example, with String row = "red,green,,blue,";, the default form row.split(",") returns [red, green, , blue]. The empty field between the two middle commas remains, but the empty field after the final comma is discarded. To preserve that final field, use row.split(",", -1), which returns [red, green, , blue, ].
A positive limit is useful when the last field may itself contain the separator. With String line = "key=value=extra";, line.split("=", 2) returns [key, value=extra]. A limit of one returns the original text as one piece because no split is made. Choose the limit based on whether the application needs every field or only an initial part and a remainder.
Empty fields and common surprises
Empty strings can be meaningful data. In a comma-separated row, "A,,C" has an empty middle field. Both split(",") and split(",", -1) keep that interior empty value. The default behavior discards only empty values at the end of the result, not all empty values.
That distinction matters when fields map to fixed positions, such as a simple record where the second column is optional. If you discard a trailing empty field, the array can be shorter than the record’s expected number of columns. Using a negative limit is often the right choice when column positions must be preserved.
Another easily missed point is that a positive-width match at the beginning of the input can produce an empty first piece. For example, splitting ":a:b" on ":" includes an empty first field. A zero-width match at the beginning is treated differently and does not create an empty leading piece. Avoid relying on complicated zero-width regex behavior unless it is needed; a clearly defined delimiter generally makes code easier to understand.
Splitting on whitespace
To split on one or more whitespace characters, a common regex is "\\s+". The plus sign groups a run of whitespace into one separator, so several spaces between words do not create a series of empty fields.
String sentence = "Java makes strings useful";
String[] words = sentence.split("\\s+");
// [Java, makes, strings, useful]
There is a leading-whitespace caveat: if the input starts with whitespace, the match at the beginning can produce an empty first element. If surrounding whitespace should be removed, prepare the input first, for example with sentence.strip().split("\\s+"). strip() is available from Java 11 and uses Java’s Unicode-aware whitespace definition; trim() is older and has different, narrower behavior.
Regex whitespace classes can also depend on regex flags and Unicode settings. If an application must recognize a particular set of international whitespace characters, define and test that requirement rather than assuming every character that looks like a space is treated identically by \\s.
When split is not the right parser
split() is appropriate when the format is simple and separators have an unambiguous meaning. It is not a full CSV parser. A CSV field can contain a comma inside quotes, and quoted fields can have escaping rules; splitting every comma would break such a record. For real CSV files, use a library that implements the format’s quoting and escaping rules.
Likewise, splitting a path, a programming-language expression, or a network protocol field may require format-specific handling. A delimiter can appear inside quoted text, escaped content, or nested structures. A regex split is not automatically a parser for those cases. Check the format specification and choose an appropriate parser when the input has those features.
Pattern.split and repeated use
For a one-off operation, String.split() is concise. If the same regex is applied repeatedly, you can compile it once as a Pattern and use its split() method. This makes the reuse explicit and avoids expressing the same pattern at each call site.
Pattern comma = Pattern.compile(",");
String[] first = comma.split("one,two,three");
String[] second = comma.split("four,five");
Pattern.split(input) also has an overload that accepts a limit. Its results follow the same limit rules described above. Prefer the approach that makes the code clearest; precompiling is most relevant when the pattern is reused, not because every small split operation needs additional setup.
Frequently Asked Questions
Does Java split take a string or a character? The argument is a string containing a regular expression, not a dedicated character parameter. A plain comma works as expected, while regex metacharacters such as a period must be escaped or quoted to mean a literal delimiter.
How do I keep empty values at the end? Use the two-argument overload with a negative limit, such as value.split(",", -1). The one-argument form uses a zero limit and removes trailing empty strings.
How do I split on a pipe character? Since a pipe means alternation in regex syntax, escape it in the Java string as "\\|", or use Pattern.quote("|") when treating a delimiter as literal text.
Why does split(".") give unexpected results? A period is a regex wildcard that can match any character. To split at literal dots, use split("\\."), or quote a dynamically supplied delimiter with Pattern.quote().
Can split parse a CSV file correctly? Not generally. Simple comma splitting cannot handle commas inside quoted fields or the full set of CSV escaping rules. Use a CSV parser for CSV data rather than treating every comma as a separator.
Related
- Enum Data Type: Meaning, Uses, and Examples
- Onshape Combine Parts Into One: Boolean Union Guide
- Excell Battery Company: What It Makes and Who It Serves
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Archive Emails in Outlook 365 Online EasilyTo archive emails in Outlook 365 online, select a message in your mailbox and choose Archive on the…
- Conditional Formatting Color Based on Value in ExcelIn Excel for Microsoft 365 on Windows, select the cells, then choose Home > Conditional Formatting and select…
- Excel Data Validation Techniques for Reliable SheetsIn Excel for Microsoft 365 on Windows, select the cells to control, then choose Data > Data Validation…
- Excel Decimal Comma: Change Number SeparatorsTo show decimal commas in Excel for Microsoft 365 on Windows, go to File > Options > Advanced,…
- Clause 34 of Tax Audit Report in Excel: What to IncludeClause 34 is a disclosure in the tax audit report, not a special Excel feature. You can prepare…
- Professional Contact List Template in Excel: Setup GuideA professional contact list template in Excel is a structured table for storing names, organizations, contact details, relationship…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.