将scala字符串转换为键值对

时间:2018-10-22 04:36:02

标签: scala parsing

如何从字符串格式将字符串值转换为键值对:

key1-value1,value2

(key1,value1),(key1,value2)?

4 个答案:

答案 0 :(得分:2)

您可以使用.split("pattern")

val data = """key1-value1,value2"""

val kv = data.split("-") match {
  case Array(h, t) =>
    t.split(",").map(value => (h, value)).toList
}

println(kv)

输出:

List((key1,value1), (key1,value2))

答案 1 :(得分:0)

@Prayagupd的回答很好,而且效果很好。此答案使用scala's split function,它与Java不同,它允许将字符数组作为输入:

val data = """key1-value1,value2"""
val t = data.split(Array(',','-'))  //gives: Array(key1, value1, value2)
t.drop(1).map(i => (t.head, i))  //Create tuples using key1 and value[i]

产生:

res0: Array[(String, String)] = Array((key1,value1), (key1,value2))

答案 2 :(得分:0)

data.split(Array('-', ',')) match { 
  case Array(k, v1, v2) => List(k -> v1, k -> v2)
}

val r = """(.+)-(.+),(.+)""".r

data match {
  r(k, v1, v2) => List(k -> v1, k -> v2)
}

答案 3 :(得分:0)

如何?

scala> val a = "key1-value1,key2-value2,key3-value3"
a: String = key1-value1,key2-value2,key3-value3

scala> a.split(",").map( x=> { val y = x.split("-");(y(0),y(1)) } ).map( x=> (x._1,x._2) ).toMap
res11: scala.collection.immutable.Map[String,String] = Map(key1 -> value1, key2 -> value2, key3 -> value3)

scala>