Sometimes you need both the pieces of a string and the separators between them. For example, a text-processing tool might need to preserve commas and semicolons while inspecting individual values.
Java 21 provides String.splitWithDelimiters() for this task.
1. Choose the separators
Our input is:
red,green;blue;
The regular expression [,;] matches either a comma or a semicolon.
Unlike split(), splitWithDelimiters() includes matched separators as elements in the returned array. See the Java 21 String API.
2. Keep the pieces and reconstruct the text
Save the following as KeepDelimitersExample.java:
import java.util.Arrays;
public class KeepDelimitersExample {
public static void main(String[] args) {
String text = "red,green;blue;";
String regex = "[,;]";
System.out.println(
"split: " + Arrays.toString(text.split(regex, -1)));
String[] parts = text.splitWithDelimiters(regex, -1);
System.out.println("keep: " + Arrays.toString(parts));
System.out.println("Rebuilt: " + String.join("", parts));
System.out.println("limit 2: " + Arrays.toString(
text.splitWithDelimiters(regex, 2)));
System.out.println("limit 0: " + Arrays.toString(
text.splitWithDelimiters(regex, 0)));
}
}
The program compares ordinary splitting with delimiter-preserving splitting. It then joins the preserved pieces without adding any extra characters.
3. Compile and run
From the directory containing the file:
javac --release 21 KeepDelimitersExample.java
java KeepDelimitersExample
Output:
split: [red, green, blue, ]
keep: [red, ,, green, ;, blue, ;, ]
Rebuilt: red,green;blue;
limit 2: [red, ,, green;blue;]
limit 0: [red, ,, green, ;, blue, ;]
The two adjacent commas in the keep line can look confusing: one is a delimiter element, while the other is punctuation added by Arrays.toString().
4. Understand the limit
The second argument controls splitting:
| Limit | Behavior |
|---|---|
| Negative | Processes all matches and preserves trailing empty strings. |
| Zero | Processes all matches but removes trailing empty strings. |
| Positive | Processes at most limit - 1 matches, leaving the remaining input together. |
With limit 2, only the first comma is processed. The result therefore contains three elements: "red", ",", and "green;blue;".
A positive limit does not directly cap the array length at that number, because delimiter elements are included. These rules are specified in the method documentation.
Best practices
- Use this method when separators carry information you need later.
- Test leading, consecutive, and trailing separators with your chosen pattern.
- Remember that the first argument is a regular expression. Use
Pattern.quote()when a user-supplied separator should be treated literally. - Use a CSV parser for quoted CSV fields; splitting on commas alone does not implement CSV rules.
Summary
splitWithDelimiters() lets you inspect string segments while preserving their separators. Choose the limit deliberately, especially when trailing empty values matter.