In Java, use String.split(regex) to divide a string wherever a regular expression matches, or use String.split(regex, limit) to control how many pieces are returned and whether trailing empty pieces are kept. For example, "red,green,blue".split(",") returns an array containing red, green, and blue.
What Java’s split() method does
split() is an instance method on Java’s String class. It searches the string for matches to a delimiter pattern, then returns the text between those matches as elements of a String[]. The delimiter is a regular expression, not necessarily a literal character. The method does not alter the original string; Java strings are immutable, and the result is a separate array.
This makes split() useful for straightforward text formats: separating words, extracting fields from a simple line, or dividing a path on a known separator. It is not a general-purpose parser. If a format allows quoted delimiters, nested structures, or escaping rules, splitting on a character alone may produce incorrect fields.
- Input:
"tea|coffee|water" - Regex delimiter:
"\\|", which matches a literal vertical bar - Result: an array with three strings:
tea,coffee, andwater
Syntax and the two overloads
There are two commonly used forms:
String[] parts = text.split(regex);String[] parts = text.split(regex, limit);
The one-argument form behaves as if the limit were zero. The two-argument form lets you choose how the result is divided. In both forms, regex is a Java regular expression. If the expression is invalid, Java throws PatternSyntaxException; if the regular-expression reference is null, the call fails with a NullPointerException.
Because the result is an array, you can access a field by index, check parts.length, or iterate over the values. A useful way to inspect an array while debugging is Arrays.toString(parts), after importing java.util.Arrays. Printing the array itself directly does not display its contents in a readable list.
Why the delimiter is a regular expression
Regular expressions make it easy to split on patterns such as one or more spaces, but they also make some simple-looking delimiters special. A comma has no special meaning in a regex, so split(",") splits at commas. A period, vertical bar, plus sign, question mark, and several other characters do have special meanings.
For example, a period in a regex means “any character,” not a literal dot. To split a version string at periods, escape the dot for the regex and also escape the backslash for the Java string literal:
String[] versionParts = "17.0.2".split("\\.");
The two backslashes in the Java source create one backslash in the regex. That regex then treats the dot as literal punctuation. For a delimiter supplied at runtime, Pattern.quote() is often clearer and safer than manually escaping regex characters:
String[] fields = text.split(Pattern.quote(delimiter), -1);
This example requires java.util.regex.Pattern. Quoting is especially useful when the delimiter might be a period, a pipe, or another character with regex meaning. It also avoids accidentally interpreting user-provided delimiter text as a pattern.
How the limit parameter changes the result
The limit parameter controls both the maximum number of array elements and the treatment of empty strings at the end. Its three cases are important:
- Positive limit: split at most
limit - 1times. The final array element contains the unsplit remainder, so the result has no more thanlimitelements. - Zero limit: split as many times as possible, then discard trailing empty elements. This is the behavior of the one-argument method.
- Negative limit: split as many times as possible and keep trailing empty elements.
For example, with "name:role:team" and the delimiter ":", a limit of 2 returns ["name", "role:team"]. This is handy when the first field has a known separator but the remainder should stay intact, such as a record with a key followed by free-form text.
Consider "alpha,beta,,". Calling split(",") returns ["alpha", "beta"], because the empty elements at the end are discarded. Calling split(",", -1) returns ["alpha", "beta", "", ""]. The empty field between the two final commas is not a trailing field, so it is retained even with the default limit.
Practical examples
For a simple comma-separated line with no quoted commas, a direct split is straightforward:
String[] columns = "Mira,28,Oslo".split(",");
The result has three elements. A program should still validate the number of fields before reading indexes such as columns[2], since malformed input may contain too few separators.
To treat runs of spaces or tabs as one separator, use a regex quantifier:
String[] words = line.trim().split("\\s+");
Here \s+ in the regex means one or more whitespace characters. Calling trim() first can prevent leading and trailing spaces from creating empty edge fields. Java’s regex definition of whitespace has specific rules; if your data includes unusual Unicode whitespace, check the regex options and behavior required by your Java version rather than assuming every visually blank character is identical.
When spaces around commas should be ignored but the commas define the fields, this pattern handles both sides:
String[] items = line.split("\\s*,\\s*");
For input such as "red, green , blue", the resulting values are red, green, and blue. This pattern consumes the surrounding whitespace as part of each separator; it does not trim unrelated whitespace at the beginning or end of the entire line.
Empty fields, leading delimiters, and edge cases
Consecutive delimiters can represent an empty field. For example, splitting "a,,b" on a comma produces ["a", "", "b"]. That empty middle value may be meaningful: in a simple table row, it could indicate a missing value. Do not automatically remove empty strings unless the data rules say they can be ignored.
A delimiter at the beginning can also produce a leading empty field when it is a positive-width match. For example, ",a,b".split(",") includes an empty first element. Zero-width regex matches have different edge behavior: Java does not add a leading empty element for a zero-width match at the beginning of the input. This distinction matters when splitting on lookarounds or other patterns that match a position without consuming a character.
If preserving every field matters, including empty values after a final delimiter, use a negative limit. If the input may be empty, test that case explicitly as part of validation. The intended result can depend on both the input and whether the regex finds a match, so boundary cases are worth including in tests rather than inferring them from ordinary examples.
Common mistakes and how to avoid them
- Using a special regex character literally:
split(".")does not mean split at periods. Escape the character, or usePattern.quote(). - Forgetting trailing empty fields are dropped: use a negative limit, such as
split(",", -1), when a final empty column is meaningful. - Assuming split understands CSV quoting: splitting
"one,"two, three"on commas does not honor the quoted comma. Use a CSV parser for CSV data. - Assuming the result has a fixed number of fields: validate its length before indexing, and decide how to handle missing or extra fields.
- Confusing a regex escape with a Java escape: a backslash often needs doubling in Java source. Work out what regex should be passed, then write the corresponding escaped Java string literal.
A related misconception is that split() removes whitespace from every returned piece. It does not. Whitespace is removed only if the regex consumes it, or if the program trims the pieces separately. For example, splitting "red, green" on a comma leaves a leading space in the second element.
Choosing between split(), Pattern, and a parser
For a small amount of ordinary text, String.split() is usually the clearest choice. It is concise, returns the array directly, and supports regex delimiters and limits. Since its argument is a regex, Java’s implementation is based on regular-expression matching rather than a special literal-character-only split operation.
If the same regex is used repeatedly in a loop, compiling a Pattern once can make that reuse explicit. A Pattern can be used to split multiple strings, while each operation uses a matcher for the input. This may be appropriate in performance-sensitive code, but measure the actual application before optimizing; readability and the number of inputs matter too.
Choose a dedicated parser when the data format has its own grammar. CSV is a common example: a field can contain a comma inside quotes, and quotes may have escaping rules. A basic split cannot reliably distinguish a separator comma from a comma inside a quoted field. The same caution applies to formats with nested delimiters, escaped separators, or multiline records.
Frequently Asked Questions
Does Java split() take a string or a regex?
It takes a regular expression as a string. A plain comma works as expected because it has no special regex meaning, but characters such as a dot or pipe must be escaped or quoted to match literally.
How do I split on a period in Java?
Use text.split("\\."). The Java string literal supplies a backslash to the regex, making the dot literal. You can also use text.split(Pattern.quote(".")).
How do I keep empty values at the end?
Pass a negative limit, for example text.split(",", -1). The one-argument form uses a zero limit, which removes trailing empty strings from the result.
What does split(regex, 1) do?
A positive limit of one means Java performs no more than zero splits and returns the input as one array element. This can be useful when code shares a configurable limit, though the ordinary unsplit string is simpler if no splitting is wanted.
Can split() parse a CSV file?
Not reliably when fields may be quoted or contain commas, escaped quotes, or line breaks. Use a CSV parser that implements the file format’s rules. Splitting is suitable only for a deliberately simpler comma-delimited string with no such features.
Practical rule of thumb
Start by writing down what counts as the separator and whether empty fields must be preserved. Use a literal delimiter directly when it is regex-safe, escape or quote it when it is not, and choose the limit deliberately if trailing fields matter. Then test representative input along with empty input, repeated delimiters, a leading delimiter, and a trailing delimiter. Those checks make the behavior of split() predictable and help reveal when the input format needs a real parser instead.
Related
- JavaScript String Length: How the length Property Works
- Access Split Forms: How They Work and When to Use One
- JavaScript String Slice: Syntax, Examples, and Common Uses
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Find Minimum Value Based on Criteria in a RangeTo find the smallest value that meets one or more conditions, use Excel’s MINIFS function. With regions in…
- Search Excel for Duplicate Entries: Methods That WorkTo search Excel for duplicate entries, select the cells you want to check, then choose Home > Conditional…
- Meal Planning Spreadsheet Template: Build a Weekly PlanA meal planning spreadsheet template is a weekly grid for choosing meals, recording recipes, and organizing the groceries…
- Flash Fill in Excel: Purpose, Examples, and LimitsFlash Fill in Excel recognizes a pattern in data you enter and fills the remaining cells to match…
- Replace in Excel: Find and Replace Text, Values, and MoreTo replace text or values in Excel, press Ctrl+H on Windows, enter the existing content in Find what…
- Excel Shortcut to Insert Cells and Shift Them DownIn Excel for Microsoft 365 on Windows, select the cell or range, press Ctrl+Shift+Plus (+)—usually Ctrl+Shift+= on a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.