简体   繁体   中英

Scala using regex with or syntax in match case statement

Cab anyone tell me why this does not work and how to fix ?

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

I expected the match statement to return "have a or b"

The actual problem is to try a series of matches on more complex regexes for an input and return a value on the first successful pattern.

The behavior you seek is:

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)

For testing just a find , don't capture the group:

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

Update: this is probably obvious, but a sequence wildcard matches whatever capture groups:

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

For regular unapply , case p() matches on true . For unapplySeq , the implementation can return a Seq or a tuple with the Seq in last position. The regex unapply returns a Seq of the matching groups, or Nil if nothing is captured.

An "anchored" regex for pattern matching matches whole inputs:

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

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

If you have capturing groups in your regex you should also use or explicitly ignore results: note _ in aorb(_) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM