Sean Nguyen
Sean Nguyen

Reputation: 13118

How to assign value to variable from a string split in groovy?

I want to assign the array item into variable directly using groovy like this:

def str = "xyz=abc"
def [name, value] = str.split("=")

but groovy doesn't like it. Is there a way to do that (not storing the array result and get the index[0], index[1] from it?).

Thanks,

Upvotes: 12

Views: 17621

Answers (2)

Eric Wendelin
Eric Wendelin

Reputation: 44349

You just need parenthesis instead of brackets:

def str = "xyz=abc"
def (name, value) = str.split("=")

enter image description here

Note that you'll need to know how many elements you're expecting or you'll have unexpected results.

Upvotes: 27

Stefan Kendall
Stefan Kendall

Reputation: 67802

def name, value
(name,value) = str.split("=")

You just need to do your definition before your multiple assignment.

Upvotes: 5

Related Questions