4

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?

3
  • 1
    In case you got this string because you do an (accidental) toString on a "real" list, you are better off preventing that. This is an accident to happen otherwise: ["1,2"].toString() => [1,2] Commented Jul 18, 2016 at 16:07
  • I need to store a list in database also return that as list ,can you give me better solution. Commented Jul 18, 2016 at 16:30
  • Use a format, that is made to (de)serialize data and pick one, that is able to hold the data type you want. E.g. for a List<String> you can use JSON. Or since you are on Grails already, why not make it a List<String> on a GORM class and just store it as what it is. Commented Jul 19, 2016 at 6:15

4 Answers 4

9

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']
Sign up to request clarification or add additional context in comments.

Comments

6

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

Perhaps simplify a bit: tokenize('[,]')
str[1..str.lenght()-2] can be simplified to str[1..-2]
2

Here you go:

String str= "['aa', 'bb', 'cc', 'dd']"
assert Eval.me(str) == ['aa', 'bb', 'cc', 'dd']

Eval is what you need.

2 Comments

If this string come from an external system, or a user, it's not really secure to use Eval for this. I prefer to use a real parser/regex for this than eval
@JérémieB, yes you're right, in such scenario it's much better to use regex.
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.