match nested parenthesis
arn.zart at gmail.com
arn.zart at gmail.com
Thu Jan 25 11:13:30 EST 2007
s99999999s2003 at yahoo.com wrote:
> hi
> i wish to find an reg exp for matching nested parenthesis of varying
> level like
> string =
> "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?
> thanks
Evaluation using re.sub() and recursion (3 lines of code):
def eval_sub(expr):
r"""Evaluate subexpressions in nested paired delimiters.
For example,
single left-pointing angle quotation ‹
single right-pointing angle quotation ›
>>> eval_sub('3 * 3 + 1 + 1 * 2')
'21'
>>> eval_sub('3 * 3 + 1 + 1 * 2') # test
mismatched delimiters
'13\x9b'
>>> '\x9b' == '' # encoding ISO-8859-1
True
>>> eval_sub('3 * 1 + 1 * 2 + 3') # test absence of
outer delimiters
'3 * 7'
"""
val, n = re.subn("([^]+)", lambda m:
str(eval(m.group(1))), expr)
if n == 0:
return val
return eval_sub(val)
#end
This is just a proof of concept.
More information about the Python-list
mailing list