Reputation: 4659
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?
Upvotes: 1
Views: 2472
Reputation: 20699
Regex is the way to go:
String res = "a, b , 55, val444".split( /\W+/ )
assert res.toString() == '[a, b, 55, val444]'
Upvotes: 0
Reputation: 295
You could use String tokenize()
(source)
assert "a, b , 55, val444".tokenize(", ") == ["a", "b", "55", "val444"]
Upvotes: 1
Reputation: 28564
String.split could accept regex
def vals_str = "a, b , 55, val444"
def vals_arr = vals_str.split(/\s*,\s*/)
Upvotes: 1
Reputation: 521103
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]
Upvotes: 1