原始字符串到元组列表

时间:2016-09-19 07:02:44

标签: scala

我有以下原始字符串,我想将其转换为List或List of tuples或List of maps,基本上我需要迭代foreach

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

使用rawStr.split(s"""[(|,|)]""").filterNot(s => s.isEmpty || s.trim.isEmpty) .grouped(2) .toList .map(pair => (pair(0), pair(1))).toList 中的任意一个分割字符串,然后分组

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).toList.map(pair => (pair(0), pair(1))).toList
res13: List[(String, String)] = List(("foo", "bar"), ("foo1", "bar1"), ("foo3", "bar3"))

Scala REPL

{{1}}

答案 1 :(得分:0)

这个也可以处理无效输入:

"\\(([^,]+{1})\\s*,\\s*([^,]+{1})\\)".r
  .findAllMatchIn(rawStr)
  .map(m => m.group(1) -> m.group(2)).toMap

你可以给它

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

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

它不会崩溃