我正在使用Python正则表达式模块,
re
.
我需要匹配这两个短语中“(' ')”内的任何内容,但“不是那么贪婪”。像这样:
show the (name) of the (person)
calc the sqrt of (+ (* (2 4) 3))
结果应该从短语 1 返回:
name
person
结果应从短语 2 返回:
+ (* (2 4) 3)
问题是,为了适应第一个短语,我使用了
'\(.*?\)'
这个,第二个短语,正好适合
+ (* (2 4)
并使用
'\(.*\)'
正确匹配第二个短语,第一个短语适合 (name) of the (person)
什么正则表达式可以正确处理这两个短语?
Pyparsing 可以轻松地为此类内容编写简单的一次性解析器:
>>> text = """show the (name) of the (person)
...
... calc the sqrt of (+ (* (2 4) 3))"""
>>> import pyparsing
>>> for match in pyparsing.nestedExpr('(',')').searchString(text):
... print match[0]
...
['name']
['person']
['+', ['*', ['2', '4'], '3']]
请注意,嵌套括号已被丢弃,嵌套文本作为嵌套结构返回。
如果您想要每个括号位的原始文本,请使用originalTextFor修饰符:
>>> for match in pyparsing.originalTextFor(pyparsing.nestedExpr('(',')')).searchString(text):
... print match[0]
...
(name)
(person)
(+ (* (2 4) 3))
这符合所有必需的信息:
(?:\()(.*?\){2})|(?:\()(.*?)(?:\))
组 1 = + (* (2 4) 3)
第 2 组 = 姓名,人
只要括号不嵌套,就可以使用惰性正则表达式:
\(.*?\)
虽然理论上您可以解析正则表达式中有限数量的嵌套,但这非常困难且不值得付出努力。使用自定义 python 函数更容易做到这一点。请参阅这个答案以获得很好的解释。