0

I need to get all expression between parenthesis in a mathematical operation, with scala.

I tried to do it with a regex. And it works with expressions like:

(2+4)-> Result: 2+4

4*(3+1)-> Result: 3+1

But It's impossible for me to get all values, as in the following example:

(2+1)*(4-3)-> Result: 2+1)*(4+3

Expected result:

`2+1`

`4+3`

Where "formula" is the input expression

    val regex = Pattern.compile("\\((.*)\\)")
    val regexMatcher = regex.matcher(formula)

    while (regexMatcher.find()) {
        println(regexMatcher.group(1)); //Fetching Group from String
    }

EDIT: In case of (1+(2+3)), the good result would be 1+(2+3)

cchantep
  • 8,797
  • 3
  • 25
  • 39
Doasy
  • 37
  • 7

2 Answers2

3
  1. You can use the reluctant quantifier *? instead of * to capture only the characters until the first ).

  2. In Scala, you don't need to double backslashes if you use triple-quoted strings, which makes regexes much more readable:

Combining:

Pattern.compile("""\((.*?)\)""")
  1. As mrzasa's answer mentions, regular expressions are a wrong tool if you ever need to handle nested parentheses (but see for a caveat How to match string within parentheses (nested) in Java? and Regular expression to match balanced parentheses).

    In Scala, you can use parser combinators instead. Huynhjl's answer to Parsing values contained inside nested brackets describes something which you can use as a starting point.

Alexey Romanov
  • 154,018
  • 31
  • 276
  • 433
2

Your regex is too greedy, it takes too much. Try

([^)]*)

this limits repetition to chars that are not a closing bracket.

In Scala it'd be probably:

    val regex = Pattern.compile("\\(([\\)]*)\\)")

Demo

Also note that this does not support nested brackets, e.g. (1+(2+3))

mrzasa
  • 21,673
  • 11
  • 52
  • 88