Scala在匹配case语句中使用正则表达式或语法

时间:2013-07-10 13:42:54

标签: scala

出租车有人告诉我为什么这不起作用以及如何解决?

val aorb = "(a|b)".r

aorb.findFirstIn("with a ")
res103: Option[String] = Some(a)

"with a " match { case aorb() => "have a or b" case _ => "None"}
res102: String = None

我希望匹配语句返回“have a or b”

实际问题是在输入的更复杂的正则表达式上尝试一系列匹配,并在第一个成功的模式上返回一个值。

2 个答案:

答案 0 :(得分:8)

您寻求的行为是:

scala> val aorb = "(a|b)".r
aorb: scala.util.matching.Regex = (a|b)

scala> val aorbs = aorb.unanchored
aorbs: scala.util.matching.UnanchoredRegex = (a|b)

scala> "with a or b" match { case aorbs(x) => Some(x) case _ => None }
res0: Option[String] = Some(a)

仅测试一个find,不要抓住该群组:

scala> val aorbs = "(?:a|b)".r.unanchored
aorbs: scala.util.matching.UnanchoredRegex = (?:a|b)

scala> "with a or b" match { case aorbs() => true case _ => false }
res4: Boolean = true

scala> import PartialFunction._
import PartialFunction._

scala> cond("with a or b") { case aorbs() => true }
res5: Boolean = true

更新:这可能很明显,但序列通配符匹配任何捕获组:

scala> val aorb = "(a|b).*(c|d)".r.unanchored
aorb: scala.util.matching.UnanchoredRegex = (a|b).*(c|d)

scala> "either an a or d" match { case aorb(_) => true case _ => false }
res0: Boolean = false

scala> "either an a or d" match { case aorb(_*) => true case _ => false }
res1: Boolean = true

对于unapply上的常规case p()true匹配。对于unapplySeq,实现可以在最后位置返回Seq或具有Seq的元组。正则表达式取消应用会返回Seq个匹配组,如果没有捕获任何内容,则返回Nil

答案 1 :(得分:7)

模式匹配的“锚定”正则表达式匹配整个输入:

val aorb = ".*(a|b).*".r

"with a " match {
  case aorb(_) => "have a or b"
  case _ => "None"
}
// res0: String = have a or b

如果您在正则表达式中有捕获组,则还应使用或明确忽略结果:请注意_中的aorb(_)