In Java, text.split(regex, -1) splits a string at every match of the regular expression and keeps empty fields at the end of the result. The negative value is the limit argument; it does not mean “split at the minus-one character” or limit the result to one piece.
What -1 means in Java
Java’s String.split method takes a regular expression and, optionally, an integer limit: split(String regex, int limit). The first argument describes where to split. The second controls how the matches are applied and what happens to empty strings at the end. A negative limit means that splitting continues as far as possible and trailing empty strings are retained.
For example, splitting "red,blue,," on a comma with a limit of -1 produces four fields: ["red", "blue", "", ""]. The two commas after blue represent two empty fields. Those fields may matter when the string represents positional data: omitting them changes the number of fields and can make later values appear to belong in the wrong columns.
The value -1 is not a special string delimiter. The delimiter is still the regular expression supplied as the first argument. The same negative-limit behavior applies whether that expression is a literal character such as a comma or a more complicated pattern.
A simple Java example
Here is a complete example that shows why the negative limit can matter:
String record = "Mira,28,";
String[] fields = record.split(",", -1);
// fields contains ["Mira", "28", ""]
System.out.println(fields.length); // 3
The final comma marks a third, empty field. With a negative limit, Java keeps it, so the array has three elements. This is useful if the empty value means something, such as an omitted final entry in a line-oriented record. If the empty field is not meaningful, the default behavior may be more convenient.
For a string with multiple trailing delimiters, each delimiter can create another empty result:
String[] parts = "a,b,,".split(",", -1);
// parts contains ["a", "b", "", ""]
There are four parts, not three: the characters between consecutive commas form empty fields, and the final comma leaves an empty field at the end. This is a common source of surprise when inspecting split results.
How the limit values differ
Java’s three categories of limit behave differently. Knowing which one you need is more reliable than treating the argument as a simple maximum number of splits.
limit > 0: the pattern is applied at mostlimit - 1times. The final array element contains the remaining text, which may itself include the delimiter.limit == 0: the pattern is applied as many times as possible, but empty strings at the end of the resulting array are discarded. Callingsplit(regex)is equivalent to callingsplit(regex, 0).limit < 0: the pattern is applied as many times as possible, and trailing empty strings are kept.
For instance, "a,b,,".split(",", 2) returns ["a", "b,,"]. Only one split is made, because a positive limit of 2 allows at most one split and two array elements. By contrast, "a,b,,".split(",") returns ["a", "b"]: splitting continues, but the empty strings at the end are removed. Using -1 returns all four fields.
Why trailing empty fields can matter
A trailing empty string is easy to mistake for nothing, but it can represent a real value in structured text. Consider a record with three comma-separated positions: a name, an age, and an optional note. In "Mira,28,", the note is blank. If code drops that final empty field, it may see only two values and treat the record as incomplete, or assign data incorrectly when processing many rows.
Keeping empty fields is also useful when checking that every row has the same number of columns. A program can split each row with -1, compare the array length with the expected field count, and then decide how to handle blank values. That is different from silently removing empty fields, which can conceal missing data.
However, split is not a complete CSV parser. Real CSV files can contain quoted commas, escaped quotes, and line breaks inside quoted fields. Splitting a CSV row on commas will incorrectly divide a value such as "Seattle, Washington". Use a CSV library when processing CSV rules; the negative limit only preserves empty results produced by Java’s regular-expression splitting.
The delimiter is a regular expression
The first argument to Java’s split method is a regular expression, not necessarily a literal string. A comma is safe as written because it has no special meaning in a Java regular expression. Other characters do have special meanings. For example, a period means “any character” in a regular expression, so text.split(".", -1) does not mean “split on periods.”
To split on a literal period, escape it for both the regular-expression engine and the Java string literal:
String[] parts = "report.final.txt".split("\\.", -1);
// parts contains ["report", "final", "txt"]
The two backslashes in the Java source produce one backslash for the regular expression, which then treats the period literally. For delimiters that are longer strings or contain several special characters, Pattern.quote can be a clearer way to create a literal-match expression. A mistaken pattern can produce unexpected splits regardless of whether the limit is negative.
Common mistakes and edge cases
- Assuming -1 means one split: it does not. A negative limit allows as many matches as possible; positive limits are the ones that cap how many splits occur.
- Using the one-argument method and expecting trailing blanks:
split(regex)uses a zero limit, so trailing empty strings are discarded. Pass -1 when those fields must remain. - Confusing leading and trailing empty fields: a delimiter at the beginning can create an empty first field. The limit’s special removal rule concerns empty fields at the end, not every empty field.
- Assuming a delimiter is literal: characters such as
.,|,*, and+have regular-expression meanings. Escape them or quote the literal delimiter.
An empty input deserves a little care. If the regular expression does not match, Java returns the input as the sole array element, even when that input is empty. Also, a zero-width regular-expression match at the start is treated differently from a positive-width match there; Java does not add an empty leading element for a zero-width match at the beginning. These details follow the regular-expression split rules, so unusual patterns are worth checking with a small example.
How other languages use -1
The meaning of a negative split argument is language-specific. In Python, str.split calls its corresponding argument maxsplit; a value of -1 means there is no maximum number of splits. With an explicit separator, Python also retains trailing empty fields: "a,b,,".split(",", -1) produces ["a", "b", "", ""]. Python’s default maxsplit is already -1, so "a,b,,".split(",") gives the same result.
JavaScript has a different API: String.prototype.split takes a separator and an optional limit for the number of array elements. It does not use Java’s negative-limit rule as its documented way to request trailing empty fields. For portable code, do not assume that split(separator, -1) means the same thing across languages. Check that language’s method definition and use its explicit no-limit or preserve-empty behavior.
Even within one language, similarly named methods can differ. When moving an algorithm between Java, Python, JavaScript, or another language, test strings with a trailing delimiter, repeated delimiters, and a delimiter at the beginning. Those cases reveal whether empty fields are preserved and whether the argument controls the number of splits or the number of returned pieces.
Choosing the right Java call
Choose the limit based on the data you need to retain, rather than using -1 automatically. If the final empty fields carry positional meaning, use -1. If trailing blanks should be ignored, the one-argument method or an explicit zero limit is appropriate. If you need to split only at the first delimiter and preserve the remainder as one field, use a positive limit such as 2.
Before relying on the result, make a small test with representative input and inspect both the array length and each element. This is especially helpful when the delimiter is a regular expression or when input can contain missing values. For a delimiter that may be present as ordinary text, quote it as a literal rather than accidentally interpreting it as a regex operator.
Frequently Asked Questions
Does split(",", -1) keep empty strings in Java?
Yes. It keeps trailing empty strings produced by splitting at commas, as well as empty fields between adjacent delimiters.
What is the difference between split(",") and split(",", -1)?
The one-argument call uses a zero limit and removes trailing empty results. A limit of -1 keeps them. Both can split at every matching comma.
Does -1 mean unlimited splitting?
In Java, a negative limit means apply the pattern as many times as possible and retain trailing empty fields. It does not restrict the split count to one.
How do I split on a dot in Java?
Use split("\\.", -1) to treat the period as a literal. A bare dot is a regex wildcard and does not mean a period character.
Is Java split suitable for CSV?
Not for general CSV data. Quoted fields may contain commas, quotes, or line breaks, which simple splitting cannot interpret correctly. Use a CSV parser for CSV files.
Related
- SQL Server STRING_AGG: Syntax, Examples, and Limits
- How to Split an Activity in P6: Step-by-Step Guide
- JavaScript String Operations: Methods and Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Not Highlighting Cells When Selected? FixesIf Excel is not visibly highlighting a selected cell, first press Esc to leave edit mode, then click…
- Excel Power Query: Keep Leading ZerosYes. To keep leading zeros in Excel Power Query, make the affected column’s data type Text before loading…
- Excel Solver Settings: How to Set Up and Choose OptionsIn Excel for Microsoft 365 on Windows, open Data > Solver, set an objective cell, choose the cells…
- How to Convert Exponential to Number in Excel: A GuideTo show an Excel value written in scientific notation as an ordinary number, select the cells and choose…
- Excel Trendlines: How to Add, Format, and Choose OneTo draw a trendline in Excel for Microsoft 365 on Windows, select a chart, click the green Chart…
- How to Add a Yes or No Checkbox in Microsoft ExcelIn Microsoft Excel for Microsoft 365 on Windows, select the cell or range where you want a checkbox,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.