Groovy Split String (2 Examples)

Groovy Split String (2 Examples)

  • Groovy
  • 1 min read

Here are the 2 examples of Groovy split string code.

Example 1: Groovy Split String (without array)

In the following example, it initializes the 4 variables and will get the string delimited by the pipe "|" into each variable:

def (value1, value2, value3, value4) = 'abc|xyz|zxc|mnb'.tokenize( '|' )
println(value1)
println(value2)
println(value3)
println(value4)

Output:

$groovy main.groovy
abc
xyz
zxc
mnb

Example 2: Groovy Split String into an Array

The below Groovy code will split the string delimited by the hyphen "-" and will get the values into an array using the for loop:

class Example {
   static void main(String[] args) {
      String a = "abc-xyz-zxc-mnb-poi-qwe";
      String[] str;
      str = a.split('-');
      
      for( String values : str )
      println(values);
   } 
}

Output:

$groovy main.groovy
abc
xyz
zxc
mnb
poi
qwe