Shirley Du
Shirley Du

Reputation: 45

Convert string representation of list to list in Scala

If I have a string representation of list s = '["a", "b", "c"]', how do I parse this string to extract the list object? Expected output l = ["a", "b", "c"]

Upvotes: 1

Views: 1594

Answers (1)

jwvh
jwvh

Reputation: 51271

val str = """["a","b" "c"]"""    // string with quote marks
val getStrs = "\"([^, ]+)\"".r   // regex to isolate quoted strings

Now to pull those quoted strings (without the quote marks) into a List[String].

val lst = (for (m <- getStrs findAllMatchIn str) yield m group 1).toList
// lst: List[String] = List(a, b, c)

Upvotes: 3

Related Questions