gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:24:08 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com