Calculate mathematical operation stored in String

2019-08-11 11:41发布

问题:

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

回答1:

If you want something flexible, this is what you need:

((?:\d+\s*[-+]\s+)*\d+)

With Live Demo