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



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

例如考虑

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

这提供了0,尽管期望的结果是 1。

非常感谢。

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

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

另外:在关于 Scala 正则表达式的更一般的 QA 中,sschaef 为模式匹配的使用提供了一个非常好的字符串插值(例如 r"col|row"在本例中)。一个潜在的警告:插值会在每次调用时创建一个新的Regex实例 - 因此,如果您多次使用相同的正则表达式,将其存储在val中可能会更有效(如本答案所示)。

不知道这是否是最好的解决方案,但有效的解决方案:

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
}

最新更新