Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use regular expression to handle nested parenthesis in math equation?

Tags:

python

regex

If I have:

statement = "(2*(3+1))*2"

I want to be able to handle multiple parentheses within parentheses for a math reader I'm writing. Perhaps I'm going about this the wrong way, but my goal was to recursively go deeper into the parentheses until there were none, and then I would perform the math operations. Thus, I would first want to focus on

"(2*(3+1))" 

then focus on

"(3+1)"

I hoped to do this by assigning the focus value to the start index of the regex and the end index of the regex. I have yet to figure out how to find the end index, but I'm more interested in first matching the regex

r"\(.+\)" 

failed to match. I wanted it to read as "any one or more characters contained within a set of parentheses". Could someone explain why the above expression will not match to the above statement in python?

like image 288
purpleladydragons Avatar asked Apr 19 '12 23:04

purpleladydragons


People also ask

How do you do nested parentheses?

Nested parentheses When you want to enclose a set of parentheses inside another set, most style guides recommend using square brackets for the inner element.

How do you use parentheses on a expression math?

For instance, you can use them to mention negative numbers when writing an addition equation. The second use of parentheses in math is to multiply numbers. If there is no arithmetic operation present in an equation, the presence of parentheses means you have to apply multiplication. Therefore, the answer is 6 x 6 = 36.

Can you do parentheses inside parentheses in math?

1. Use brackets inside parentheses to create a double enclosure in the text. Avoid parentheses within parentheses, or nested parentheses.

Can you use parentheses in regex?

Use Parentheses for Grouping and Capturing. By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.


1 Answers

I love regular expressions. I use them all the time.

Don't use regular expressions for this.

You want an actual parser that will actually parse your math expressions. You might want to read this:

http://effbot.org/zone/simple-top-down-parsing.htm

Once you have actually parsed the expression, it's trivial to walk the parse tree and compute the result.

EDIT: @Lattyware suggested pyparsing, which should also be a good way to go, and might be easier than the EFFBot solution posted above.

https://github.com/pyparsing/pyparsing

Here's a direct link to the pyparsing sample code for a four-function algebraic expression evaluator:

http://pyparsing.wikispaces.com/file/view/fourFn.py

like image 88
steveha Avatar answered Oct 01 '22 23:10

steveha