I want to evaluate mathematical expression stored in String and print the result.
I have to use Pattern matching in Scala.
I wrote this code below, but it does not work, it prints false instead of 2.
Any help will be appreciated.
object PatternMatcher{
val s = "13 - 5 - 6"
val Pattern = "((\\d+\\s[+-]\\s){1,10}(\\d+){0,1})".r
def main(args: Array[String]) {
println(matcher(s))
}
def matcher(choice: String): Any = choice match {
case Pattern(choice) => choice
case _ => "false"
}
}
\\d+\\s[+-]\\s){1,10}\\d+) i got only5 -as a result, which is the last part of the string matched with the pattern.(\d+\s+[-+]\s+\d+\s+[-+]\s+\d)(to be escaped) does it work?