Java String split(): Tokenizing Text with Regex Delimiters & Limits

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 & The Two Overloaded Signatures 🔝

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.

2. Basic Delimiter Splitting Examples 🔝

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

3. Controlling Split Count with Positive Limit 🔝

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/2026

Terminal Output:

Part 0: 22
Part 1: 05/2026

4. Trailing Empty Elements: Default (0) vs. Negative (-1) Limit 🔝

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);  // 6

Terminal Output:

Default split length: 3
limit = -1 length:    6

5. Escaping Special Regex Delimiters: Dots, Pipes, and Slashes 🔝

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

6. Comparison: String.split() vs. StringTokenizer vs. Scanner 🔝

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()).

7. Production Recipe: Splitting Key-Value Configuration Lines 🔝

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

8. Practical Recipe: Multi-Delimiter Sentence Tokenizer 🔝

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]

9. Practical Recipe: Email Address Username and Domain Extractor 🔝

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

10. Common Developer Pitfalls & Traps 🔝

The Unescaped Period Dot Trap

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(".")).

The Silent Discard of Trailing Empty Fields

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).

11. Complete Compilable Java Program 🔝

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!

12. Frequently Asked Questions (FAQ) 🔝

How do I split a string by pipe delimiter '|'?

Because | represents the OR operator in regex, escape it with double backslashes: str.split("\\|").

What happens when splitting an empty string ""?

Calling "".split(",") returns a 1-element array containing a single empty string: [""].

Is split() performance-intensive?

Yes. split() compiles a regular expression pattern on every call. For fast single-character tokenizing, consider indexOf() loops or a precompiled Pattern.

What happens if the delimiter is not found in the string?

If the delimiter pattern does not match, split() returns a 1-element array containing the entire original string.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer