使用分隔符拆分字符串

我目前正在尝试拆分一个字符串 1128-2,以便我可以有两个独立的值。例如 value1:1128和 value2:2,这样我就可以分别使用每个值。我试过 split(),但没有成功。Grails 是否有一种特定的方法来处理这个问题,或者有更好的方法来处理这个问题?

325282 次浏览

Try:

def (value1, value2) = '1128-2'.tokenize( '-' )

How are you calling split? It works like this:

def values = '1182-2'.split('-')
assert values[0] == '1182'
assert values[1] == '2'

def (value1, value2) = '1128-2'.split('-') should work.

Can anyone please try this in Groovy Console?

def (v, z) =  '1128-2'.split('-')


assert v == '1128'
assert z == '2'

split doesn't work that way in groovy. you have to use tokenize...

See the docs:

http://groovy-lang.org/gdk.html#split()

You can also do:

Integer a = '1182-2'.split('-')[0] as Integer
Integer b = '1182-2'.split('-')[1] as Integer


//a=1182 b=2
dependencies {
compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
def (g, m) = i.tokenize( ':' )
dep.exclude group: g  , module: m
}
}
}