need some regular expression help

Diez B. Roggisch deets at web.de
Sat Oct 7 18:00:29 EDT 2006


Chris wrote:
> I need a pattern that  matches a string that has the same number of '('
> as ')':
> findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [
> '((2x+2)sin(x))', '(log(2)/log(5))' ]
> Can anybody help me out?

This is not possible with regular expressions - they can't "remember"
how many parens they already encountered.

You will need a real parser for this - pyparsing seems to be the most
popular choice today, I personally like spark. I'm sure you find an
example-grammar that will parse simple arithmetical expressions like
the one above.

Diez




More information about the Python-list mailing list