Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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,

like image 285
Sean Nguyen Avatar asked Mar 28 '12 20:03

Sean Nguyen


People also ask

How do you split a string and assign it to a variable?

Splitting a String by comma (,) Here, the variable str is declared with a string with commas (“,”) in between them. The Split function is implemented with “,” as the separator. Whenever the function sees a comma character, it separates the string and the output is a list of substrings between the commas in str.

How do I assign a value to a variable in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.


1 Answers

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.

like image 198
Eric Wendelin Avatar answered Oct 25 '22 01:10

Eric Wendelin