Matching Parenthetical with Regular Expressions

I am working on a math expression parser using regular expressions and I am trying to add parenthesis support.

My parser works as follows:

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
}

Since it is recursive, I need to find only the extreme brackets. For example, if I were 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?

Now the regular expression ("\ (([^ \)] +) \)") will return only "5 + (4 + (3 * 2"), it will not receive the full first expression and it will not receive even a second.

Any ideas?

Thanks,

Kyle

+3
4

, , , . , :

(\([^(]+\))

, .. , (3 / 4), (3 * 2) (1 + 2). 0,75, 6 3 , :

(5 + (4 + 0,75 + 6 + 2)) + 3

, , , ( , ​​!)

, , , , (, ) . , .

+5

, .

, - , , () . , .

" " ( perl) , .

- . , , , , , - .

, , , , , (1 + 2) +3 1+ (2 + 3), 1 + 2 + 3.

+6

, , .

+2

You must use the parser. Ask the parser to cross the line and increase the number of parentheses each time it encounters (and decrease the counter each time it hits a). when it will dial a zero score, you have the range of your outer expression in parentheses.

+2
source

Source: https://habr.com/ru/post/1726324/


All Articles