ofirule
ofirule

Reputation: 4659

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

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

Answers (5)

injecteer
injecteer

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

aspok
aspok

Reputation: 295

You could use String tokenize() (source)

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

Upvotes: 1

daggett
daggett

Reputation: 28564

String.split could accept regex

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

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

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

ofirule
ofirule

Reputation: 4659

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()

Upvotes: 2

Related Questions