I am working on a math expression parser using regular expressions and I am trying to add support for parentheses.
My parser works like this:
function parse_expression(expression){
Find parenthetical expressions
Loop through parenthetical expressions, call parse_expression() on all of them
Replace parenthetical expression with value of expression
Find value of expression
Return value
}
Because it it recursive, I need to find only the outmost parenthetical expressions. For example if I was parsing the string “(5 + (4 + (3 / 4) + (3 * 2) + 2)) + (1 + 2)”, I want to find the expressions “5 + (4 + (3 / 4) + (3 * 2) + 2)” and “1 + 2”. How do you do this with Regular Expressions?
The regular expression I have now ( “\(([^\)]+)\)” ) would return just “5 + ( 4 + ( 3 * 2”, it doesn’t get the full first expression and it gets none of the second.
Any ideas?
Thanks,
Kyle
Since you’re iterating through it all, I’d say you should still do that, but go the other way around. Find the smallest subsets of paranthetical expressions, rather than the largest ones:
Evaluate them, and replace them with their values, i.e., first time round, the matches will be
(3 / 4),(3 * 2)and(1 + 2). Replace these with0,75,6and3, respectively, giving a new string:And then you iterate that, until there are no more parenthetical expressions, working bottom-up rather than top-down (just like you would manually solve a task like this!)
Other than that, I agree with all others that exactly what you were asking for should not (indeed could not) be done with regular expressions. But your problem could be solved with this solution that involves regular expressions.