The String.split() method splits a string into an array of substrings around matches of a specified regular expression pattern.
Regex Slicing & Array Tokenization: Java allows fine-grained control over output array size and trailing empty strings using the limit parameter. To re-assemble tokens with a delimiter, explore String.join(). For literal replacements without regex, see replace(), or slice text with substring().
1. Syntax & Overloads 2. Basic Delimiter Splitting 3. Controlling Split Count 4. Trailing Empty Elements 5. Escaping Special Delimiters 6. split vs. StringTokenizer 7. Key-Value Config Recipe 8. Multi-Delimiter Recipe 9. Email Parser Recipe 10. Common Traps 11. Compilable Demo 12. FAQ Further Reading
Java provides two overloaded methods in java.lang.String to tokenize text:
// 2 Overloaded signatures of split() in java.lang.String
public String[] split(String regex)
public String[] split(String regex, int limit)
| Signature | Parameters | Operational Behavior |
|---|---|---|
split(String regex) |
regex (Pattern) |
Splits around regex matches. Discards trailing empty strings (equivalent to split(regex, 0)). |
split(String regex, int limit) |
regex, limit (int) |
Controls the maximum array length and controls whether trailing empty elements are retained. |
Splitting date strings, paths, or structured records into an array of components:
String date = "22/05/2026";
String[] tokens = date.split("/");
for (int i = 0; i < tokens.length; i++) {
System.out.println("Element " + i + ": " + tokens[i]);
}Terminal Output:
Element 0: 22
Element 1: 05
Element 2: 2026
Passing a positive limit restricts the number of resulting elements. The remainder of the string is preserved in the final element:
String str = "22/05/2026";
// limit = 2 splits at the first delimiter, keeping remainder intact
String[] parts = str.split("/", 2);
System.out.println("Part 0: " + parts[0]); // 22
System.out.println("Part 1: " + parts[1]); // 05/2026Terminal Output:
Part 0: 22
Part 1: 05/2026
When data rows end with empty fields (e.g. "a,b,,,"), standard split(",") silently drops trailing values. Use a negative limit (-1) to retain all fields:
String csv = "apple,banana,cherry,,,";
// 1. Default split(regex) or limit = 0: Discards trailing empty elements!
String[] defaultSplit = csv.split(",");
System.out.println("Default split length: " + defaultSplit.length); // 3
// 2. Negative limit (limit = -1): Retains all trailing empty elements!
String[] keepAllSplit = csv.split(",", -1);
System.out.println("limit = -1 length: " + keepAllSplit.length); // 6Terminal Output:
Default split length: 3
limit = -1 length: 6
Because the argument is interpreted as a regular expression, characters with special regex meaning must be escaped with \\:
String ip = "192.168.1.1";
// WRONG: "." is a regex wildcard matching every single character!
String[] wrong = ip.split(".");
System.out.println("ip.split('.'): length = " + wrong.length); // 0 (all chars matched!)
// CORRECT: Escape the dot using double backslashes
String[] correct = ip.split("\\.");
System.out.println("ip.split('\\.'): length = " + correct.length); // 4 (192, 168, 1, 1)Terminal Output:
ip.split('.'): length = 0
ip.split('\.'): length = 4
Comparing tokenization strategies across Java applications:
| Tool | Delimiter Support | Primary Use Case & Notes |
|---|---|---|
String.split() |
Full regular expressions. | Modern, standard choice for parsing text arrays and CSV strings. |
StringTokenizer |
Single literal characters only. | Legacy class (Java 1.0). Fast but lacks regex support and empty token preservation. |
Scanner |
Regex patterns & types. | Streaming I/O parser that reads typed tokens directly (e.g., nextInt()). |
Splitting on the first delimiter only ensures values containing the delimiter character remain intact:
String config = "db.connection.url=jdbc:mysql: // localhost:3306/prod_db";
// Use limit = 2 to avoid splitting on '=' inside URLs or connection values
String[] kv = config.split("=", 2);
System.out.println("Key: " + kv[0]);
System.out.println("Value: " + kv[1]);Terminal Output:
Key: db.connection.url
Value: jdbc:mysql://localhost:3306/prod_db
Tokenizing natural language text across spaces, commas, semicolons, and periods simultaneously:
String sentence = "Java,Spring;Hibernate RESTful API.";
// Split by one or more whitespace, commas, semicolons, or dots
String[] words = sentence.split("[\\s,;.]+");
for (String w : words) {
System.out.println("Word: [" + w + "]");
}Terminal Output:
Word: [Java]
Word: [Spring]
Word: [Hibernate]
Word: [RESTful]
Word: [API]
Separating the user account handle from the email domain name:
String email = "support@plus2net.com";
String[] parts = email.split("@");
System.out.println("Username: " + parts[0]);
System.out.println("Domain: " + parts[1]);Terminal Output:
Username: support
Domain: plus2net.com
Calling str.split(".") matches every single character because . is the regex wildcard. The resulting array is completely empty. Always write str.split("\\.") or str.split(Pattern.quote(".")).
Calling "a,b,,".split(",") yields an array of size 2, not 4. Trailing empty strings are dropped by default. When parsing CSV columns where trailing cells may be empty, always pass -1 as the limit: split(",", -1).
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringSplitFullDemo {
public static void main(String[] args) {
String data = "alpha|beta|gamma||";
// 1. Escaped pipe delimiter with negative limit
String[] tokens = data.split("\\|", -1);
if (tokens.length == 5 && tokens[0].equals("alpha")) {
System.out.println("Check 1 Passed: Pipe delimiter and trailing empties verified.");
}
// 2. Default limit discards trailing empty strings
String[] trimmed = data.split("\\|");
if (trimmed.length == 3) {
System.out.println("Check 2 Passed: Default limit discarded trailing empties.");
}
// 3. Positive limit caps array size
String[] limited = data.split("\\|", 2);
if (limited.length == 2 && limited[1].equals("beta|gamma||")) {
System.out.println("Check 3 Passed: Limit capped array size to 2 elements.");
}
System.out.println("All String.split() verification checks passed successfully!");
}
}Terminal Output:
Check 1 Passed: Pipe delimiter and trailing empties verified.
Check 2 Passed: Default limit discarded trailing empties.
Check 3 Passed: Limit capped array size to 2 elements.
All String.split() verification checks passed successfully!
Because | represents the OR operator in regex, escape it with double backslashes: str.split("\\|").
Calling "".split(",") returns a 1-element array containing a single empty string: [""].
Yes. split() compiles a regular expression pattern on every call. For fast single-character tokenizing, consider indexOf() loops or a precompiled Pattern.
If the delimiter pattern does not match, split() returns a 1-element array containing the entire original string.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.