Pangea Pangea - 2 months ago 6
Groovy Question

String.split not counting the last empty elements

Look at the following 2 examples. How to make sure the 2nd one prints 4 as well?

String s="a|b|c|d"
println(s.split("\\|").length)
//prints 4

s="a|b||"​​​​​​​​​​​​
println(s.split("\\|").length)​
//prints 2

Answer

To keep the empty token, use split with limit = -1

println(s.split("\\|", -1).length)​