1

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"
    }
}
4
  • A capturing group inside a capturing group...? Is that what you wanted to do ? Commented Jan 27, 2016 at 13:21
  • @Thomas I think yes, because I want to capture whole string. When i used one group( \\d+\\s[+-]\\s){1,10}\\d+) i got only 5 - as a result, which is the last part of the string matched with the pattern. Commented Jan 27, 2016 at 13:29
  • If you try with this: (\d+\s+[-+]\s+\d+\s+[-+]\s+\d) (to be escaped) does it work? Commented Jan 27, 2016 at 13:31
  • @Thomas Oh, I didn't mention that i want to expand this equation, by adding or subtract more numbers. So your solution works but only for this example, with 3 numbers. Commented Jan 27, 2016 at 13:48

1 Answer 1

1

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

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

With Live Demo

Sign up to request clarification or add additional context in comments.

5 Comments

I'm getting exception: Unknown inline modifier near index 3 ((?|\d+\s*[-+]\s+)*\d+) It points on | (logical OR)
@user3463645 the regex I gave you is unescaped, you should escape it before using it (using \ )
I can't get it to work, could you write exactly how the Pattern variable should look like.
@user3463645 my bad. It's a : instead of |
Great, now it's working. I have used """((?:\d+\s*[-+]\s+)*\d+)""" so there is no need to escape string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.