split()
Splits a String around matches of a regular expression into an array, with a limit that controls how many parts and empty trailing fields you get.
public String[] split(String regex, int limit)- Added in Java Java 1.4
Parameters
| Parameter | Type | Description |
|---|---|---|
$regex | String | The delimiter as a regular expression. |
$limitoptional | int= 0 | If positive, at most limit parts and the last keeps the rest. If 0, trailing empty strings are removed. If negative, all parts are kept. |
Return value
String[]The parts of the String between matches of regex. With no match, an array holding the whole String.
Errors
PatternSyntaxException if regex is invalid; NullPointerException if regex is null.
Changelog
- PHP Java 8A zero-width match at the beginning of the String no longer produces an empty leading element.
- PHP Java 21splitWithDelimiters(String regex, int limit) was added, which also returns the matched delimiters.
split(regex) cuts a String at every match of a regular expression and returns the pieces as a String[]. It is the quickest way to read a comma-separated header, a query string or a simple config line, and it has three behaviours that cause most bugs.
1. The delimiter is a regex
"a.b.c".split(".") returns an empty array, because . matches every char and everything is a delimiter. split("|") splits between every char. Escape the metacharacter ("\\.", "\\|") or use Pattern.quote. The JDK has a fast path for a single plain char such as ",", so simple delimiters are cheap.
2. Trailing empty fields disappear
With the default limit of 0, empty strings at the end are removed: "a,b,,".split(",") has 2 elements, not 4. For CSV-like data where position matters, that shifts or drops columns. Pass a negative limit, split(",", -1), to keep every field. Empty fields in the middle and at the start are always kept.
3. A positive limit stops early
split("=", 2) returns at most two parts, and the second keeps everything after the first =. That is exactly what you want for key=value pairs where the value may contain =, such as Base64 padding or a JDBC URL.
Other details
"".split(",")returns an array with one empty String, not an empty array. Check for blank input first.- Split on whitespace with
"\\s+"afterstrip(), otherwise leading whitespace produces an empty first element. - Java 21 added
splitWithDelimiters, which returns the delimiters between the parts, handy for tokenisers.
split is not a CSV parser: it cannot handle quoted fields that contain the delimiter. For real CSV, use a library or a small state machine. In a hot loop, a static final Pattern with pattern.split(s) avoids recompiling non-trivial expressions.
Example
When to use it
- Reading the values of a comma-separated Accept or X-Forwarded-For header.
- Turning a query string or form body into a map of parameters.
- Parsing KEY=VALUE lines from a .env file where values may contain '='.
Frequently asked questions
Why does split(".") return an empty array?
The argument is a regular expression and . matches any char, so every char is a delimiter and only empty strings remain, which are then removed as trailing empties. Use split("\\.") or split(Pattern.quote(".")).
How do I keep empty strings at the end when splitting?
Pass a negative limit: s.split(",", -1). With the default limit of 0, trailing empty strings are dropped from the result.
How do I split by a pipe character in Java?
Escape it: s.split("\\|") or s.split(Pattern.quote("|")). An unescaped | is an empty alternation, which matches between every char.
More examples
Parsing a query string
The limit of 2 keeps any '=' inside a value, and a parameter with no '=' still gets an entry. Values are percent-decoded after splitting, because decoding first could turn %26 into an extra '&'.
void main() {
String query = "page=2&name=Ada%20L&q=&flag";
Map<String, String> params = new LinkedHashMap<>();
for (String pair : query.split("&")) {
String[] kv = pair.split("=", 2);
String value = kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : "";
params.put(kv[0], value);
}
IO.println(params);
}
// Output:
// {page=2, name=Ada L, q=, flag=}Splitting on a regex metacharacter
An unescaped | is an empty alternation in a regular expression, so it matches between every char. Escaping it or wrapping it in Pattern.quote makes it a literal pipe; Pattern.quote is the safer choice when the delimiter comes from configuration.
void main() {
String line = "42|Ada|admin";
IO.println(Arrays.toString(line.split("|")));
IO.println(Arrays.toString(line.split("\\|")));
IO.println(Arrays.toString(line.split(Pattern.quote("|"))));
}
// Output:
// [4, 2, |, A, d, a, |, a, d, m, i, n]
// [42, Ada, admin]
// [42, Ada, admin]Limits and keeping the delimiters (Java 21)
A limit of 3 stops after two cuts and leaves the rest in the last element. splitWithDelimiters returns operators between operands, which is what a small expression or filter parser needs, while a leading delimiter still gives an empty first element.
void main() {
IO.println(Arrays.toString("a:b:c:d".split(":", 3)));
IO.println(Arrays.toString("12+3*4-5".splitWithDelimiters("[+*-]", 0)));
IO.println(Arrays.toString(",a,b".split(",")));
}
// Output:
// [a, b, c:d]
// [12, +, 3, *, 4, -, 5]
// [, a, b]
Discussion