[英]How to split a String delimited by space in groovy
I am trying to separate my String using spaces and extract the second text of the String value.我正在尝试使用空格分隔我的字符串并提取字符串值的第二个文本。
Here is my code -这是我的代码 -
String title = 'testing abcdefgh.abc.cde.fgh test testing issue'
String[] test = title.split(" ");
String[] newTest = test[1];
println newTest
Here is the output i am getting - [a, b, c, d, ., a, b, c, ., c, d, e, ., f, g, h]这是我得到的 output - [a, b, c, d, ., a, b, c, ., c, d, e, ., f, g, h]
NOw the output i am looking for is abcd.abc.cde.fgh, but i am getting [a, b, c, d, ., a, b, c, ., c, d, e, ., f, g, h]现在我正在寻找的 output 是 abcd.abc.cde.fgh,但我得到 [a, b, c, d, ., a, b, c, ., c, d, e, ., f, g , H]
I have used ("\s+"), ("\s"), just a space inside brackets, single and double quotes enclosing a space, nothing works.我用过(“\s+”),(“\s”),只是括号内的一个空格,单引号和双引号包围一个空格,没有任何作用。
It's because here 因为这里
String[] newTest = test[1]
You tell groovy to stick the string you want into a string array 您告诉groovy将所需的字符串粘贴到字符串数组中
So groovy tries to do what you say, and splits the characters out into separate strings 因此,groovy尝试按照您说的做,然后将字符分成单独的字符串
What you want is just a string, not a string array. 您想要的只是一个字符串,而不是字符串数组。 Try 尝试
String newTest = test[1]
Instead 代替
I think the problem is that in Java you have to escape a backslash in a String literal.我认为问题在于,在 Java 中,您必须转义 String 文字中的反斜杠。 So while the pattern you want is \s+
, you have to put this in Java as "\\s+"
因此,虽然您想要的模式是\s+
,但您必须将其作为"\\s+"
放入 Java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.