Abhinandan Aithal
Abhinandan Aithal

Reputation: 171

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]

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]

I have used ("\s+"), ("\s"), just a space inside brackets, single and double quotes enclosing a space, nothing works.

Upvotes: 1

Views: 19224

Answers (2)

xpusostomos
xpusostomos

Reputation: 1641

I think the problem is that in Java you have to escape a backslash in a String literal. So while the pattern you want is \s+, you have to put this in Java as "\\s+"

Upvotes: 0

tim_yates
tim_yates

Reputation: 171084

It's because here

String[] newTest = test[1]

You tell groovy to stick the string you want into a string array

So groovy tries to do what you say, and splits the characters out into separate strings

What you want is just a string, not a string array. Try

String newTest = test[1]

Instead

Upvotes: 6

Related Questions