Groovy — Splitting and trimming strings
Groovy can split a string into at most two parts. Set the split limit to two so later equals signs stay in the value, then trim each field.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
def parts = "a=b".split("=")
println(parts[1])
b
Split one setting into a key and a value
The positive split limit allows at most two parts. The remainder of the line stays together even if it contains another equals sign. Check the length before indexing.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
def parts = ' city = Lima '.split('=', 2)
if (parts.size() == 2) {
println(parts[0].trim() + '=' + parts[1].trim())
}
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.