Java String.splitWithDelimiters
Split at regular-expression matches and retain each matching delimiter in the result.
A simple example
String.splitWithDelimiters
- Start with "a,b"
- Do this Split and keep the comma
- Result a, comma, b
class Main {
public static void main(String[] args) throws Exception {
System.out.println(java.util.Arrays.toString("a,b".splitWithDelimiters(",", 0)));
}
}
[a, ,, b]
Syntax
public String[] splitWithDelimiters(String regex, int limit)
JDK 21 method signatures (1)
public String[] splitWithDelimiters(String regex, int limit)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaKeep punctuation when editing a route
A transit editor changes selected text in a route while preserving its remaining stops or punctuation. Identify which occurrences belong to the requested edit before rebuilding the public route label.
class Main {
public static void main(String[] args) throws Exception {
String route = "A->B/C";
System.out.println(java.util.Arrays.toString(route.splitWithDelimiters("->|/", -1)));
}
}
[A, ->, B, /, C]
The arrow and slash survive as separate elements, so the original punctuation can be rebuilt.
Retain a blank last field and its separator
A timetable or route import divides each record at separators. Test the behavior at an empty field so later columns do not shift when the writer leaves a value blank.
class Main {
public static void main(String[] args) throws Exception {
String row = "tea;";
System.out.println(java.util.Arrays.toString(row.splitWithDelimiters(";", -1)));
}
}
[tea, ;, ]
Both the final semicolon and the empty field after it are represented.
Keep the slashes on a sign
A designer wants to edit each word and preserve the original separators. Split on the slash while keeping each matched separator in the result. Which tokens does the editor receive?
What to watch for
Available in JDK 21. Positive limits restrict splitting and a negative limit keeps trailing empty strings.