string 用分隔符拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16450680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:54:57  来源:igfitidea点击:

Splitting String with delimiter

stringgroovysplit

提问by thehoule64

I am currently trying to split a string 1128-2so that I can have two separate values. For example, value1: 1128 and value2: 2, so that I can then use each value separately. I have tried split()but with no success. Is there a specific way Grails handles this, or a better way of doing it?

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

回答by tim_yates

Try:

尝试:

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

回答by ataylor

How are you calling split? It works like this:

你怎么打电话split?它是这样工作的:

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

回答by dmahapatro

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

def (value1, value2) = '1128-2'.split('-')应该管用。

Can anyone please try this in Groovy Console?

任何人都可以在 Groovy 控制台中尝试这个吗?

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

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

回答by davidddp

You can also do:

你也可以这样做:

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

//a=1182 b=2

回答by Angstrom Beebe

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

split 在 groovy 中不能那样工作。你必须使用标记化...

See the docs:

查看文档:

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

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

回答by qwas

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
     }
   }
}