Java splits a string with text.split(regex) or text.split(regex, limit), returning an array of substrings separated by matches of a regular expression. The separator is a regex, not necessarily a literal character, and the optional limit controls how many pieces are returned and whether trailing empty pieces are kept.
The Basic String.split Syntax
The String class provides two commonly used overloads. The first takes a regular-expression string; the second takes that expression plus an integer limit:
String[] pieces = text.split(regex);String[] pieces = text.split(regex, limit);
For example, "red,green,blue".split(",") returns an array containing red, green, and blue. The comma marks the boundary, so it is not included in any returned element. The result type is always a String[], even if the input contains no matching separator.
There is no split(char) overload in String. A single ordinary character can still be passed as a one-character regex, but special regex characters need attention. Java also has Pattern.split, which applies a compiled regex to input; it is useful when the same pattern is reused repeatedly.
Why the Separator Is a Regular Expression
Java implements string splitting using regex matching. That makes patterns such as "," convenient, but means a separator like a period does not mean “a literal period.” In regex syntax, a period matches almost any character. To split on a literal dot, escape it for both the regex engine and the Java string literal: String[] parts = filename.split("\\.");. The two backslashes in Java source form one backslash for the regex.
Other regex metacharacters include *, +, ?, |, parentheses, square brackets, braces, and the backslash itself. For example, split("|") is not a safe way to split on a pipe: the pipe means alternation in regex syntax. Escape it as split("\\|"), or quote a variable delimiter with Pattern.quote.
When the separator comes from user input or another variable and should be treated literally, quoting is usually the clearest approach:
String[] parts = text.split(Pattern.quote(delimiter), -1);
Add import java.util.regex.Pattern; when using that class. Quoting prevents characters inside the delimiter from being interpreted as regex operators. It does not trim the returned pieces or otherwise normalize the input.
What the Limit Parameter Changes
The limit argument determines the maximum number of times the pattern is applied and how the result handles empty strings at the end. The rules are often the source of surprising results:
- A positive limit splits at most
limit - 1times. The last element contains the unsplit remainder, which can itself contain separators. - A zero limit applies the pattern as many times as possible, then discards trailing empty strings. This is the behavior of the one-argument
split(regex)call. - A negative limit applies the pattern as many times as possible and keeps trailing empty strings.
For instance, "one,two,three".split(",", 2) produces ["one", "two,three"]. With "a,,b,".split(",", -1), the result is ["a", "", "b", ""]. The empty element between the two adjacent commas represents a missing field; the last empty element represents the final comma.
By contrast, "a,,b,".split(",") discards the final empty element and returns ["a", "", "b"]. It does not remove the empty element in the middle. If empty trailing fields matter—for example, when parsing a simple delimited record—use a negative limit.
Practical Patterns and Examples
For a string containing words separated by one or more whitespace characters, a regex such as "\\s+" matches each run of whitespace. In Java source the backslash is doubled because it must first be represented in a string literal:
String[] words = sentence.trim().split("\\s+");
The call to trim() is optional and has its own behavior: it removes certain characters from the ends before splitting. Without trimming, leading whitespace can produce an empty first item when the separator match has positive width at the beginning. If preserving the original whitespace or exact boundaries matters, do not trim automatically.
To split a line on tabs, use "\\t"; for one or more tabs, use "\\t+". To split on a sequence of one or more commas or semicolons, a character class can be used, such as "[,;]+". That pattern treats consecutive separators as one boundary, so it will not preserve an empty field between adjacent commas. Choose the expression based on whether repeated separators represent one separator or missing data.
For a simple key-value string with a single equals sign, a positive limit can keep later equals signs in the value: "mode=fast=careful".split("=", 2) returns ["mode", "fast=careful"]. This is useful when the first separator has special meaning but the remainder should stay together.
Leading, Trailing, and Empty Matches
With a positive-width regex match at the beginning of a nonempty input, splitting can produce an empty first element. For example, ":start".split(":") begins with an empty string followed by start. This represents the text before the first separator, even though there is no text there.
A zero-width match behaves differently: Java does not create an empty leading element for a zero-width match at the beginning. This matters for patterns that match positions rather than consuming characters, such as some lookarounds. If a pattern seems to produce an unexpected first field, check whether it consumes characters or only identifies a position.
An empty input string is another edge case. Splitting "" on a delimiter that does not match still yields an array containing the original empty string. In general, do not infer whether a field exists by looking only at the printed array: an empty string is a valid array element, while an array with no elements is a different result. Inspect the array length and each element when empty input has meaning in the application.
Common Mistakes and Data-Parsing Limits
- Forgetting regex escaping: A dot, pipe, or other metacharacter may match something different from the literal delimiter intended. Escape it or call
Pattern.quote. - Using the default limit without checking the data: The one-argument form drops trailing empty fields. Use a negative limit when those fields carry meaning.
- Assuming split trims values: A value such as
" red, blue "retains spaces around the pieces. Trim each element separately if that is actually required. - Expecting CSV parsing: Splitting on commas is not a complete CSV parser. It cannot correctly handle quoted commas, escaped quotation marks, or all CSV line-ending rules.
- Assuming multiple separators always preserve blanks: A regex such as
"[,;]+"consumes a run of separators as one match. That is different from splitting on a single comma, which can leave empty fields between adjacent commas.
For structured formats such as CSV, JSON, or configuration files with quoting and escaping, use a parser designed for that format rather than accumulating increasingly complicated split expressions. For a small, controlled string format, document the delimiter rules and test empty fields, repeated delimiters, and unexpected input.
Choosing Between String.split and Alternatives
Use String.split when the input is a manageable string, the separator is naturally described by a regex, and an array of all results is convenient. If the same expression is applied to many strings, compile it once with Pattern.compile and call the resulting pattern’s split method. This makes the reuse explicit and avoids expressing the pattern anew at each call site.
For a fixed literal delimiter and very large input, a manual search with methods such as indexOf can offer more control over allocation and field handling, though it requires more code and careful boundary logic. StringTokenizer is an older alternative with different semantics: it treats delimiters as individual characters and does not return empty tokens by default, so it is not a drop-in replacement for split.
Java 21 added String.splitWithDelimiters(regex, limit), which returns the delimiters as well as the text pieces, alternating between them. It can help when the separators themselves need to be retained. For applications targeting earlier Java versions, that method is unavailable; capture groups or a matcher-based approach may be appropriate depending on the pattern and desired output.
Frequently Asked Questions
Does Java split take a string or a character?
It takes a regex represented as a String, not a char. A one-character delimiter can be passed as a string, but regex metacharacters must be escaped or quoted if they should be literal.
How do I split on a dot in Java?
Use text.split("\\.") for a literal dot in Java source, or text.split(Pattern.quote(".")). The backslash form escapes the dot for the regex engine; Java source requires the backslash itself to be escaped.
How do I keep empty values at the end?
Pass a negative limit, for example text.split(",", -1). The default zero limit removes trailing empty strings, which can otherwise make a record with a final delimiter appear to have fewer fields.
Why does split return fewer fields than expected?
Common causes are a regex that matches more characters than intended, a default zero limit that drops trailing empty values, or a delimiter that does not occur in the input. Check the regex, the limit, and the original string; print each returned value with visible markers to reveal spaces and empty strings.
Does split handle CSV correctly?
No, not in the general case. A comma split cannot recognize commas inside quoted fields or CSV escaping rules. Use a CSV parser for actual CSV data; split is suitable only for a simpler format whose delimiter rules exclude those cases.
Related
- JavaScript split() Method: Turn a String Into an Array
- SQL Server STRING_AGG: Syntax, Examples, and Limits
- How to Split an Activity in P6: Step-by-Step Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Undo Shortcut: Keys, Limits, and How It WorksIn Excel for Microsoft 365 on Windows, press Ctrl+Z to undo your most recent action. On a Mac,…
- Enum Value: How to Get It in Common LanguagesTo get an enum value, select a member and access the value representation your language defines: in C#,…
- Excel Freeze Panes at Selection: Steps, Limits, and TipsTo freeze panes at a selection in Excel for Microsoft 365 on Windows, select the cell just below…
- Named Ranges in Excel: How They Work and How to Use ThemA named range in a spreadsheet is a descriptive label assigned to a cell or group of cells;…
- Google Sheets Timestamp: How to Create OneTo create a fixed timestamp in Google Sheets, select a cell and press Ctrl+; to insert the date,…
- Resize a Picture in an Excel Header: Step-by-StepTo resize a picture in an Excel header, open the header in Page Layout view, insert the picture,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.