python - 正则表达式:匹配括号贪婪和非贪婪

标签 python regex regex-greedy

我正在使用 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/

相关文章:

python - cProfile 需要很长时间

python - Python中的正则表达式从右到左解析

用于匹配从 0.00 到 50.00 的数字的正则表达式

regex - 非空间空间

javascript - 匹配以特定单词开头和结尾的所有摘录

regex - Grep 所有不以#(哈希)或贪心空格和#(哈希)开头的行

javascript - 正则表达式,用于匹配包含一个单词但不包含另一个单词的URL

python - 由于 pip/distribute 错误,Heroku 推送被拒绝。解决方法是什么?

python - MySQL备份-警告密码不安全

python - 修改 numpy 数组以获取元素之间值的最小数量