Home > OS >  How can i split string to list using scala
How can i split string to list using scala

Time:09-20

i has string str = "one,two,(three,four), five"

I want to split this string into list, like this: List[String] = ("one", "two", "(three, four)", "five")?

i have no idea for this.

thanks

CodePudding user response:

We can try matching on the pattern \(.*?\)|[^, ] :

val str = "one,two,(three,four), five"
val re = """\(.*?\)|[^, ] """.r
for(m <- re.findAllIn(str)) println(m)

This prints:

one
two
(three,four)
five

This regex pattern eagerly first tries to find a (...) term. That failing, it matches any content other than comma or space, to consume one CSV term at a time. This trick avoids the problem of matching across commas inside (...).

  • Related