In Java, splitWithDelimiters(regex, limit) works like split, but the matched delimiters are kept: the result alternates between the text pieces and the delimiters that separated them.
That makes it easy to break text into tokens without losing the operators or punctuation, for example turning "12+3*45" into numbers and operators, and then rebuild the original by joining everything back together.
splitWithDelimiters() is an instance method of java.lang.String, added in Java 21. Call it on a string, as in text.splitWithDelimiters(...); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed. Requires Java 21 or newer.
Syntax
Pass a regex and a limit; there is no single-argument overload.
The limit counts splits, not array elements: a limit of n > 0 applies the pattern at most n - 1 times, giving up to 2n - 1 elements. With 0, trailing empty strings are removed; with a negative value, everything is kept.
Library declarations
java
public String[] splitWithDelimiters(String regex, int limit);
Parameters
Parameter
Description
regex
The delimiting regular expression.
limit
Positive caps the number of splits, 0 drops trailing empty strings, negative keeps everything.
Return Value
Return Value
Description
String[]
Text pieces and delimiters, alternating, starting with a text piece.
Java Examples
Example 1 — Split and Keep the Delimiters
Compare the result with plain split.
java
import java.util.Arrays;
public class SplitWithDelimitersBasic {
public static void main(String[] args) {
String text = "a,b,c";
String[] kept = text.splitWithDelimiters(",", 0);
System.out.println(Arrays.toString(kept));
System.out.println(kept.length + " vs " + text.split(",").length);
System.out.println(String.join("", kept));
}
}
Output
[a, ,, b, ,, c]
5 vs 3
a,b,c
How It Works
Delimiters become elements. Each comma appears in the array between the letters, which Arrays.toString prints as ,, with its own separator.
More elements than split. Three pieces plus two delimiters give 5 elements, versus 3 from split.
Lossless. Joining every element with an empty separator rebuilds exactly "a,b,c".
Example 2 — Tokenize an Arithmetic Expression
A character class of operators separates the numbers and keeps the operators.
java
import java.util.Arrays;
public class SplitWithDelimitersTokens {
public static void main(String[] args) {
String expr = "12+3*45-6";
String[] tokens = expr.splitWithDelimiters("[+*/-]", 0);
System.out.println(Arrays.toString(tokens));
for (int i = 1; i < tokens.length; i += 2) {
System.out.println("operator " + tokens[i]);
}
}
}