简体   繁体   中英

How to get the list from a string in Groovy?

I have string listString = "test1 test-2 [test-3, test-4]"

Is there a way to get the list from the string

I tried to fetch the list using the below code, but it only returns the last value from the string test-4] , which is incorrect

toutput = listString.substring(listString.lastIndexOf(' ') + 1)

Expected output [test-3, test-4]

Once I get the expected output, I want loop through the output list to get the values from the list

Sample code:

for (o in toutput){
  println(o) // test-3 and test-4
}

Any help would be appreciated

Thank You

This should give you the expected answer:

def listString = "test1 test-2 [test-3, test-4] test5 [test6, test7]"

def lastItem = (listString.split( '([ ](?=\\[))|(\\][ ])')).last()

assert lastItem == '[test6, test7]'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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