Adam Shakhabov
Adam Shakhabov

Reputation: 1356

Regular expression for a mathematic expression

I am trying to parse the following mathematical expressions by the single regular expression:

2(3(4+5)6)7
3(4+5)6

The expression should return (3(4+5)6)7 for the first example and (4+5)6 for the second. I created this:

[\(\[].*[\(\]]*\d*

but it is true only for the first case.

Is it possible to create a single regular expression for the above cases?

Upvotes: 0

Views: 71

Answers (1)

The fourth bird
The fourth bird

Reputation: 163457

You can match the first ( and the last ) followed by only optional digits and specify the allowed characters in between.

\([\d+()-]+\)\d*

Regex demo

If you can make use of PCRE, you could match balanced parenthesis and match the optional trailing digits.

(\((?>[\d+-]|(?1))*\))\d*

Regex demo

Upvotes: 1

Related Questions