Rajesh
Rajesh

Reputation: 5

Split Variable using groovy script

I'm very much new to groovy scripting. I have a requirement and need to split the string into different varaibles.

eg: 100546_2018_03_100900100546_YDE4567832.xml

V1 : 100546
V2 : 2018
V3 : 03
V4 : 100900100546_YDE4567832.xml

Can you please help me in getting code snippet.

Upvotes: 0

Views: 1803

Answers (4)

cfrick
cfrick

Reputation: 37008

You can solve this by spliting with _ up to 4 elements. E.g.

def s = "100546_2018_03_100900100546_YDE4567832.xml"
def (v1, v2, v3, v4) = s.split("_", 4) // XXX
println([v1,v2,v3,v4].inspect())
// => ['100546', '2018', '03', '100900100546_YDE4567832.xml']

Upvotes: 5

Nitin Dhomse
Nitin Dhomse

Reputation: 2612

The following code is as per your expected result.

String str = "100546_2018_03_100900100546_YDE4567832.xml"
List versionList =  str.tokenize("_")
println "v1 : "+versionList[0]+", v2 : "+​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​versionList[1]+​", v3 : "+versionList[2]+​", v4 : "+versionList[3]+​"_"+​​​​​​versionList[4]​

Demo is here : https://groovyconsole.appspot.com/script/5176945876664320

Upvotes: 0

sarkasronie
sarkasronie

Reputation: 345

def (v1, v2, v3, v4part1, v4part2) = '100546_2018_03_100900100546_YDE4567832.xml'.tokenize('_')
def v4 = v4part1 + '_' + v4part2

Upvotes: 0

daggett
daggett

Reputation: 28564

def s="100546_2018_03_100900100546_YDE4567832.xml"
def v=s.split("_")
println v[0] // prints 100546
println v[1] // prints 2018
println v[2] // prints 03
println v[3] // prints 100900100546
println v[4] // prints YDE4567832.xml

Upvotes: 1

Related Questions