Java Reference ยท java.lang
Java String.split() method
Reference for Java String.split(): split a string by a regular expression, the limit argument, trailing empty strings, escaping special characters.
String.split() breaks a string into an array of substrings around matches of a regular expression. It is the usual first step for parsing comma-separated values, words in a sentence or key-value pairs.
The separator is a regex, not a plain string, so characters like ., | and + have special meaning and must be escaped. Another surprise: trailing empty strings are removed from the result unless you pass a negative limit.
"a,b,c".split(","); // ["a", "b", "c"] "a1b22c".split("\\d+"); // ["a", "b", "c"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public String[] split(String regex) public String[] split(String regex, int limit)
| Name | Description |
|---|---|
regex |
A regular expression that marks the separators. |
limit |
Positive: at most limit parts, the last holds the rest. Zero (default): as many parts as possible, trailing empty strings removed. Negative: as many parts as possible, trailing empty strings kept. |
Returns: a new array. If the regex never matches, the array holds just the original string.
Throws: PatternSyntaxException for an invalid regex; NullPointerException for null arguments.
Usage notes
- Escape metacharacters.
.,|,$,^,*,+,?,(,),[,{and\need\\(a backslash in the regex, written as two in a Java literal), or wrap the text inPattern.quote(). - Trailing empty strings vanish with the default limit:
"a,b,,".split(",")has length 2. Pass-1to keep them (useful for CSV with empty last fields). - Leading empty string. A match at index 0 with width greater than zero gives a leading
"". A zero-width match at the start does not (Java 8+), so"abc".split("")is["a", "b", "c"]. - Empty input.
"".split(",")returns[""](length 1), but",".split(",")returns an empty array. - Fast path. Single-character separators that are not regex metacharacters skip the regex engine and are fast.
- Compile once for loops.
String.splitcompiles the pattern every call; in hot code use a staticPatternandpattern.split(text). - Keep the delimiters with Java 21's
splitWithDelimiters(regex, limit), or use lookarounds. - Whitespace:
trim()orstrip()first, then split on"\\s+", to avoid a leading empty element. - Real CSV (quoted fields, embedded commas) needs a proper parser, not
split(). - Stream form:
Pattern.splitAsStream()gives a lazyStream<String>.