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?
4 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']
Comments
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..:)
2 Comments
railsdog
Perhaps simplify a bit: tokenize('[,]')
Gergely Toth
str[1..str.lenght()-2] can be simplified to str[1..-2]Here you go:
String str= "['aa', 'bb', 'cc', 'dd']"
assert Eval.me(str) == ['aa', 'bb', 'cc', 'dd']
Eval is what you need.
toStringon a "real" list, you are better off preventing that. This is an accident to happen otherwise:["1,2"].toString() => [1,2]