简体   繁体   English

在Groovy中将String转换为arrayList

[英]Convert String to arrayList in groovy

I have a string like: String str = "[aa,bb,cc,dd]" . 我有一个字符串: String str = "[aa,bb,cc,dd]" I want to convert this to a list in groovy like [aa, bb, cc, dd] . 我想将它转换为groovy中的列表,如[aa, bb, cc, dd] Any groovy method available for this type conversion? 任何可用于此类型转换的groovy方法?

Using regexp replaceAll 使用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']

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..:) 希望能帮助到你..:)

Here you go: 干得好:

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

Eval is what you need. Eval就是您所需要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM