How can a recursive regexp be implemented in pytho

2019-01-04 13:00发布

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"

4条回答
神经病院院长
2楼-- · 2019-01-04 13:19

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']
查看更多
SAY GOODBYE
3楼-- · 2019-01-04 13:27

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

查看更多
神经病院院长
4楼-- · 2019-01-04 13:39

This is an old question, but for the people who come here through searches:

There's an alternative regex module for python that does support recursive patterns: https://pypi.python.org/pypi/regex

And it has a lot of more nice improvements on re.

查看更多
5楼-- · 2019-01-04 13:41

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

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

查看更多
登录 后发表回答