为什么同一匹配器的匹配行为不同?
val str = "project git commit: da2837ec0a"
val Expr = "([a-f0-9]{10})$".r
scala> str match { case Pattern(c) => c; case _ => "no match" }
res30: String = no match
scala> (Pattern findFirstIn str).get
res31: String = da2837ec0a
答案 0 :(得分:10)
使用带模式匹配的正则表达式时,必须匹配整个字符串。如果不希望出现这种情况,您可以将其设为 unanchored 正则表达式:val Pattern = "whatever".r.unanchored
相比之下,findFirstIn
会在字符串中的任何位置查找匹配项 - 因此在您的示例中不需要unanchored
才能匹配。
API reference中记录了这一点,这对于这些问题通常很有帮助。