regex for balanced parentheses?

David C. Ullrich dullrich at
Thu Jun 12 13:06:10 CEST 2008

There's no regex that detects balanced parentheses,
or is there?

That is, search('and so ((x+y)+z) = (x+(y+z))')
should return '((x+y)+z)'.

Not just a theoretical question, I'm cleaning up
a large body of TeX code and a regex that did that
would be very convenient. (Yes, I know it's not
hard to detect balanced parentheses by hand...)

I don't know that stuff, but I seen to recall reading
that there's a theoretical notion of "regular expression"
in CS, and a regular expression in that sense cannot
do this. But in the same place I read that the actual
regexes in programming languages include things which
are not regular expressions in that theoretical sense.

David C. Ullrich

More information about the Python-list mailing list