parenthesis

pds at quadstone.com pds at quadstone.com
Tue Nov 5 08:19:57 EST 2002


> On 4 Nov 2002 22:05:11 GMT, bokr at oz.net (Bengt Richter) wrote:
> 
> >On 4 Nov 2002 12:24:31 -0800, mis6 at pitt.edu (Michele Simionato) wrote:
> >
> >>Suppose I want to parse the following expression:
> >>
> >>>>> exp='(a*(b+c*(2-x))+d)+f(s1)'
> >>
> >>I want to extract the first part, i.e. '(a*(b+c*(2-x))+d)'.
> >>

The method I've used in perl (! sorry, new to python :) with some success is to 
generalize your routine that tracks the nesting level but actually modifies the 
string to insert escaped versions of the parens.  ie. call with something like:

escape_paren('(a*(b+c*(2-x))+d)+f(s1)','()') 

where second arg is optional two character string with the opening and closing 
brackets.

this returns a string like:

'<QL0>a*<QL1>b+c*<QL2>2-x<QR2><QR1>+d<QR0>+f<QL0>s1<QR0>'

then you can do whatever you like with regexp, and call an inverse routine

unescape_paren(escaped_str,'()')

to put back the parens (obviously the routines also need to handle (un)escaping 
things that look like escaped parens).

Patrick





More information about the Python-list mailing list