Scala字符串模式由多个可能的组匹配

时间:2014-08-18 09:54:10

标签: string scala pattern-matching scala-collections

给定输入Map[String,String],例如

val in = Map("name1"                -> "description1",
             "name2.name22"         -> "description 22",
             "name3.name33.name333" -> "description 333")

提取每个名称和每个描述的简单方法是什么,并将它们提供给方法,例如

def process(description: String, name: String*): Unit = name match {
  case Seq(n)     =>  // find(n).set(description)
  case Seq(n,m)   =>  // find(n).find(m).set(description)
  case Seq(n,m,o) =>  // find(n).find(m).find(o).set(description)
  case _          =>  // possible error reporting
}

非常感谢

2 个答案:

答案 0 :(得分:2)

您可以使用splat运算符_*

val in = Map("name1" -> "description1",
  "name2.name22" -> "description 22",
  "name3.name33.name333" -> "description 333")

def process(description: String, name: String*) = ???


in.map { x =>
  process(x._2, x._1.split("\\."): _*)
}

请注意,*参数必须位于函数签名的最后(否则编译器将无法决定停止的位置)。

来自REPL:

scala>   def process(description: String, name: String*) = {
     |     name.foreach(println)
     |     println(description)
     |   }
process: (description: String, name: String*)Unit

scala>   in.map { x =>
      |    process(x._2, x._1.split("\\."): _*)
      |   }
    name1
    description1
    name2
    name22
    description 22
    name3
    name33
    name333
    description 333

答案 1 :(得分:1)

您可以执行以下操作:

in foreach { case (ns, d) => process(d, ns.split("\\."): _*) }