match nested parenthesis

Neil Cerutti horpner at yahoo.com
Tue Jan 23 11:46:48 EST 2007


On 2007-01-23, s99999999s2003 at yahoo.com <s99999999s2003 at yahoo.com> wrote:
> hi
> i wish to find an reg exp for matching nested parenthesis of
> varying level like
> string =

It is not possible, because the set of strings containing
balanced parenthesis is not regular. Python re's aren't *really*
regular expressions, so you might be able to hack something up
using extensions (I'm not sure if it's been proven that you
can'). I believe regexes are the wrong tool for the job.

> "somewords1(words(somewords2)-(some(some)words3)somestuff)somestuff"
> and be able to evaluate the pair starting from the inner
> most(the deepest level) , ie (some) up till the outer most.
> What is a good reg exp to do this? or is simple string
> manipulations enough? 

Write a context free grammar and a recognizer for that grammar,
instead. Python developers haven't been able to agree on any such
module to include in the standard distribution yet,
unfortunately. But fortunately (consequently), there are tons of
nice parser and scanner generators available on the net. Try
pyparsing for a start, as it's a recent, maintained package with
excellent support on this group at the moment.

Or just compose your own little function by hand. A stack-based
solution (implemented using a list as a stack) should be easy enough.

-- 
Neil Cerutti
And now the sequence of events in no particular order. --Dan Rather

-- 
Posted via a free Usenet account from http://www.teranews.com




More information about the Python-list mailing list