你所尋求的行爲是:
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
。
總結senia的答案,它是*匹配*,而不是「搜索」或「查找」。整個監票字符串必須與RE匹配,而不僅僅是其中的一部分。 –
這是一個很好的助記符(說實話),如果它是真的。實際上,在未綁定的正則表達式中,未應用會執行「find」。 –
@ som-snytt:對不起,事實並非如此。 Scala的'Regex'類中的提取器/'unapply',就是這裏所說的,它固有地固定在兩端。 –