Reputation: 713
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?
Upvotes: 4
Views: 21634
Reputation: 20707
another way w/o replaceAll & tokenize:
def s = '[aa,bb,cc,dd]'
def a = []
s.eachMatch( /[\[]?([^\[\],]+)[,\]]?/ ){ a << it[ 1 ] }
assert '[aa, bb, cc, dd]' == a.toString()
Upvotes: 0
Reputation: 6976
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']
Upvotes: 9
Reputation: 23835
You should try as below :-
String str = "[aa,bb,cc,dd]"
assert str[1..str.length()-2].tokenize(',') == ['aa', 'bb', 'cc', 'dd']
Hope it helps..:)
Upvotes: 6
Reputation: 84864
Here you go:
String str= "['aa', 'bb', 'cc', 'dd']"
assert Eval.me(str) == ['aa', 'bb', 'cc', 'dd']
Eval
is what you need.
Upvotes: 2