views:

219

answers:

3

I'm interested how can be implemented recursive regexp matching in Python (I've not found any examples :( ). For example how would one write expression which matches "bracket balanced" string like "foo(bar(bar(foo)))(foo1)bar1"

A: 

Unfortunately I don't think Python's regexps support recursive patterns.

You can probably parse it with something like pyparsing: http://pyparsing.wikispaces.com/

reko_t
+2  A: 

You can't do it with a regexp. Python doesn't support recursive regexp

gnibbler
+4  A: 

You could use pyparsing

#!/usr/bin/env python
from pyparsing import nestedExpr
import sys
astring=sys.argv[1]
if not astring.startswith('('):
    astring='('+astring+')'

expr = nestedExpr('(', ')')
result=expr.parseString(astring).asList()[0]
print(result)

Running it yields:

% test.py "foo(bar(bar(foo)))(foo1)bar1"
['foo', ['bar', ['bar', ['foo']]], ['foo1'], 'bar1']
unutbu