Nitesh Virani Nitesh Virani - 1 year ago 82
Scala Question

Raw string to list of tuples

I have below raw string and I want to convert it to List or List of tuples or List of maps, basically I need to iterate through foreach

val rawStr = "(foo,bar), (foo1,bar1), (foo3,bar3)"

How would I go for it?

Answer Source

Split the string using any of ( , ) and then group

rawStr.split(s"""[(|,|)]""").filterNot(s => s.isEmpty || s.trim.isEmpty)
.map(pair => (pair(0), pair(1))).toList

Scala REPL

scala> val rawStr = "(foo,bar), (foo1,bar1), (foo3,bar3)"
rawStr: String = "(foo,bar), (foo1,bar1), (foo3,bar3)"

scala> rawStr.split(s"""[(|,|)]""").filterNot(s => s.isEmpty || s.trim.isEmpty).grouped(2) => (pair(0), pair(1))).toList
res13: List[(String, String)] = List(("foo", "bar"), ("foo1", "bar1"), ("foo3", "bar3"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download