有没有办法在scala中匹配字符串,如下所示:
def matcher(arg: String) : Expr = {
case left :: '*' :: right => new Binary("*", left, right)
case left :: '+' :: right => new Binary("+", left, right)
}
哪里左右都有String类型?
答案 0 :(得分:9)
您可以通过匹配正则表达式来实现目标。
trait Expr
case class Binary(op: String, leftOperand: String, rightOperand: String) extends Expr
val mulPattern = "(\\d*)\\*(\\d*)".r
val addPattern = "(\\d*)\\+(\\d*)".r
def matcher(arg: String) : Expr = {
arg match {
case mulPattern(left, right) => new Binary("*", left, right)
case addPattern(left, right) => new Binary("+", left, right)
}
}
def main(args: Array[String]): Unit = {
println(matcher("1+2")) // Binary("+", "1", "2")
println(matcher("3*4")) // Binary("*", "3", "4")
}
答案 1 :(得分:2)
我不这么认为。
如果您将String
转换为List
或Vector
Char
,然后使用mkString
恢复结果,则可以执行此操作。但是我无法想出一些东西。
然而,imo,正则表达式会更简洁和可读:
trait Expr
case class Binary(op: String, left: String, right: String) extends Expr
val Expression = """(.*?)\s*([+-\/\^\*])\s*(.*)""".r
def matcher(arg: String) : Expr = arg match {
case Expression(left, op, right) => new Binary(op, left, right)
}
val test = matcher("a + b")
val test2 = matcher("a * b")
答案 2 :(得分:1)
您也可以使用提取器执行此操作:
object Mult {
def unapply(x: String): Option[(String, String)] = x.split("\\*") match {
case Array(a: String, b: String) => Some(a -> b)
case _ => None
}
}
object Add {
def unapply(x: String): Option[(String, String)] = x.split("\\+") match {
case Array(a: String, b: String) => Some(a -> b)
case _ => None
}
}
def matcher(arg: String) = arg match {
case Mult(left, right) => Binary("*", left, right)
case Add(left, right) => Binary("+", left, right)
case _ => println("not matched")
}
您可能还想为每个提取器实现apply方法,如:
def apply(l: String, r: String) = s"$l*$r"
但这不是强制性的