使用正则表达式进行Scala数组模式匹配

时间:2014-03-03 12:46:42

标签: arrays string scala pattern-matching

如何使用正则表达式对数组中的第一个字符串元素进行模式匹配?

考虑例如

Array("col",1) match {
  case Array("""col | row""", n, _*) => n
  case _ => 0
}

传递0,但期望的结果是1。

非常感谢。

2 个答案:

答案 0 :(得分:7)

Regex实例会自动提供提取器,因此您可以直接在模式匹配表达式中使用它:

val regex = "col|row".r

Array("col",1) match {
  case Array(regex(), n, _*) => n
  case _ => 0
}

另外:在Scala中关于regexp的更一般的QA中,sschaef有provided a very nice string interpolation for pattern matching usage(例如在此示例中为r"col|row")。一个潜在的警告:插值会在每次调用时创建一个新的Regex实例 - 因此,如果您多次使用相同的正则表达式,那么可能会更高效地将其存储在{ {1}}代替(如本回答所述)。

答案 1 :(得分:2)

不知道这是否是最佳解决方案,而是工作方式:

Array("col", 1) match {
  case Array(str: String, n, _*) if str.matches("col|row") => n //note that spaces are removed in the pattern
  case _ => 0
}