Library contents

Java String.splitWithDelimiters

Split at regular-expression matches and retain each matching delimiter in the result.

A simple example

String.splitWithDelimiters

  1. Start with "a,b"
  2. Do this Split and keep the comma
  3. Result a, comma, b
The result stores the delimiter as its own element between the two fields.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(java.util.Arrays.toString("a,b".splitWithDelimiters(",", 0)));
    }
}
Output
[a, ,, b]

Syntax

Java 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.java

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

From the programString route = "A->B/C"
Result[A, ->, B, /, C]
Main.java
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)));
    }
}
Output
[A, ->, B, /, C]

The arrow and slash survive as separate elements, so the original punctuation can be rebuilt.

Advertisements

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.

From the programString row = "tea;"
Result[tea, ;, ]
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String row = "tea;";
        System.out.println(java.util.Arrays.toString(row.splitWithDelimiters(";", -1)));
    }
}
Output
[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?

GivenART/LAB
Worked resultART · / · LAB

What to watch for

Available in JDK 21. Positive limits restrict splitting and a negative limit keeps trailing empty strings.

Documentation for String.splitWithDelimiters