要定义自定义匹配,您需要定义一个提取器(带有unapply
方法的对象)。实现它需要解析字符串。这是一些使用解析器组合器执行此操作的代码:
case class StringAndNumber(string: String, number: Int)
object Test {
def unapply(s: String): Option[StringAndNumber] = Parser(s)
}
object Parser extends scala.util.parsing.combinator.RegexParsers {
def apply(s: String): Option[StringAndNumber] =
parseAll(stringAndNumber, s) match {
case Success(x, _) => Some(x)
case _ => None
}
lazy val stringAndNumber = string ~ number ^^
{ x => StringAndNumber(x._1, x._2) }
lazy val string = "[^0-9]*".r
lazy val number = "[0-9]+".r ^^ { _.toInt }
}
def foo(s: String): String = s match {
case "str" => "str"
case Test(san) => s"${san.string}|${san.number}"
case _ => "?"
}
// prints: "str, str|2, ?"
println ( Seq("str", "str2", "2str").map(foo(_)).mkString(", ") )