Calculate mathematical operation stored in String using regex in Scala

天大地大妈咪最大 提交于 2019-12-24 17:19:59

问题


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



来源:https://stackoverflow.com/questions/35037985/calculate-mathematical-operation-stored-in-string-using-regex-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!