我正在使用 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))
关于python - 正则表达式:匹配括号贪婪和非贪婪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6071784/