Scala, pattern matching, strings

Is there a way to match strings in scala like this:

def matcher(arg: String) : Expr = { case left :: '*' :: right => new Binary("*", left, right) case left :: '+' :: right => new Binary("+", left, right) } 

where is the type of String left and right?

+5
source share
3 answers

You can achieve your goal by matching regular expressions.

 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") } 
+9
source

I do not think so.

You might be able to do this if you convert String to List or Vector from Char , and then return the results using mkString . But I can’t think of something.

However, imo, the regex will be more concise and readable:

 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
source

You can also do this with extractors:

 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") } 

You can also apply the apply method for each extractor, for example:

 def apply(l: String, r: String) = s"$l*$r" 

but this is optional

+1
source

Source: https://habr.com/ru/post/1233412/


All Articles