Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to arrayList in groovy

Tags:

grails

groovy

I have a string like: String str = "[aa,bb,cc,dd]". I want to convert this to a list in groovy like [aa, bb, cc, dd]. Any groovy method available for this type conversion?

like image 384
Sayem Avatar asked Dec 04 '22 00:12

Sayem


1 Answers

Using regexp replaceAll

String str = "[aa,bb,cc,dd]"
def a = str.replaceAll(~/^\[|\]$/, '').split(',')
assert a == ['aa', 'bb', 'cc', 'dd']

EDIT:

The following version is a bit more verbose but handles extra white spaces

String str = " [ aa , bb , cc , dd ] "
def a = str.trim().replaceAll(~/^\[|\]$/, '').split(',').collect{ it.trim()}
assert a == ['aa', 'bb', 'cc', 'dd']
like image 67
Gergely Toth Avatar answered Feb 15 '23 14:02

Gergely Toth