Library contents

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

Syntax

Groovy 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.groovy

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

Result[A, /, B, :, C]
Lesson.groovy
println "A/B:C".splitWithDelimiters("[/:]", -1).toList()
Output
[A, /, B, :, C]

Stops and separators alternate in the result.

Advertisements

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.

Result3
Lesson.groovy
println "paid;".splitWithDelimiters(";", -1).length
Output
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?

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