How to split and trim a sting with groovy in one line

Viewed 53

I have a string with values sperated by the , char. e.g:

vals_str = "a, b ,    55,  val444"

and I would like to generate the following array:

vals_arr = ["a", "b", "55", "val444"]

How can I do it with groovy in one line?

5 Answers

You could also use a findAll() approach here:

vals_str = "a, b ,    55,  val444"
vals_arr = vals_str.findAll("[^,\\s]+")
println vals_arr  // [a, b, 55, val444]

String.split could accept regex

def vals_str = "a, b ,    55,  val444"
def vals_arr = vals_str.split(/\s*,\s*/)

Inspired by link

I was able to achieve the wanted solution in two ways:

1.

vals_str = "a, b ,    55,  val444"
vals_arr = vals_str.split(",").collect{ it.trim() }
vals_str = "a, b ,    55,  val444"
vals_arr = vals_str.split(",")*.trim()

You could use String tokenize() (source)

assert "a, b ,    55,  val444".tokenize(", ") == ["a", "b", "55", "val444"]

Regex is the way to go:

String res = "a, b ,    55,  val444".split( /\W+/ )
assert res.toString() == '[a, b, 55, val444]'
Related