Groovy 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
Syntax
public String[] splitWithDelimiters(String regex, int limit)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyRetain the shape of 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.
println "A/B:C".splitWithDelimiters("[/:]", -1).toList()
[A, /, B, :, C]
Stops and separators alternate in the result.
Count parts including a blank field
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.
println "paid;".splitWithDelimiters(";", -1).length
3
The text, delimiter and empty final field all survive.
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.