Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala, pattern matching, strings

Is there 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 left and right are have type String?

like image 648
DoSofRedRiver Avatar asked Oct 10 '15 11:10

DoSofRedRiver


People also ask

Can you pattern match on a string Scala?

Pattern matching is a powerful feature of the Scala language. It allows for more concise and readable code while at the same time providing the ability to match elements against complex patterns.

Does Scala have pattern matching?

Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.

How does Scala pattern matching work?

Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.

What is case _ in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .


1 Answers

You can achieve your goal by matching on 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")
} 
like image 92
Till Rohrmann Avatar answered Oct 13 '22 14:10

Till Rohrmann