为了匹配嵌套结构,一些正则表达式方言提供递归模式,如(?R)
. 这个(?R)
东西基本上是说“这个表达式匹配的东西”。
标准 pythonre
不支持这一点,但最终将替换的较新的正则表达式re
模块支持。这是一个完整的例子。
text = """
{{some text}}
some other text
{{Infobox President
birth|d/m/y
other_inner_text:{{may contain {curly} bracket}}
other text}}
some other text
or even another infobox
{{Infobox Cabinet
same structure
{{text}}also can contain {{}}
}}
can be some other text...
"""
import regex
rx = r"""
{{ # open
( # this match
(?: # contains...
[^{}] # no brackets
| # or
}[^}] # single close bracket
| # or
{[^{] # single open bracket
| # or
(?R) # the whole expression once again <-- recursion!
)* # zero or more times
) # end of match
}} # close
"""
rx = regex.compile(rx, regex.X | regex.S)
for p in rx.findall(text):
print 'FOUND: (((', p, ')))'
结果:
FOUND: ((( some text )))
FOUND: ((( Infobox President
birth|d/m/y
other_inner_text:{{may contain {curly} bracket}}
other text )))
FOUND: ((( Infobox Cabinet
same structure
{{text}}also can contain {{}}
)))
有关递归正则表达式的详细说明,请参阅此博客条目。
![在此处输入图像描述](https://i.stack.imgur.com/IkMgV.jpg)
(忍不住偷了这个)。
也就是说,使用基于解析器的解决方案可能会更好。例如,请参阅使用 pyparsing 解析嵌套表达式。