In article <[EMAIL PROTECTED]>, "Chris" <[EMAIL PROTECTED]> 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? > > Thanks for any help! Why does it need to be a regex? There is a very simple and well-known algorithm which does what you want. Start with i=0. Walk the string one character at a time, incrementing i each time you see a '(', and decrementing it each time you see a ')'. At the end of the string, the count should be back to 0. If at any time during the process, the count goes negative, you've got mis-matched parentheses. The algorithm runs in O(n), same as a regex. Regex is a wonderful tool, but it's not the answer to all problems. -- http://mail.python.org/mailman/listinfo/python-list