need some regular expression help

hanumizzle hanumizzle at
Sun Oct 8 04:00:50 CEST 2006

On 7 Oct 2006 15:00:29 -0700, Diez B. Roggisch <deets at> wrote:
> 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.

Remember that regular expressions are used to represent regular
grammars. Most regex engines actually aren't regular in that they
support fancy things like look-behind/ahead and capture groups...IIRC,
these cannot be part of a true regular expression library.

With that said, the quote-unquote regexes in Lua have a special
feature that supports balanced expressions. I believe Python has a
PCRE lib somewhere; you may be able to use the experimental ??{ }
construct in that case.

-- Theerasak

More information about the Python-list mailing list