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

问题描述 投票:0回答:4

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

什么正则表达式可以正确处理这两个短语?

python regex regex-greedy
4个回答
8
投票

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))

0
投票

你想要做的事情看起来像一个调车场(实际上它看起来像LISP,所以也许你应该检查一下PyLisp)。不需要使用正则表达式来解析此类表达式。

参见调车场文章@维基百科,它是Python实现


0
投票

这符合所有必需的信息:

(?:\()(.*?\){2})|(?:\()(.*?)(?:\))

组 1 = + (* (2 4) 3)

  • 最后一个“)”可以用 .strip(')') 去掉

第 2 组 = 姓名


-3
投票

只要括号不嵌套,就可以使用惰性正则表达式:

\(.*?\)

虽然理论上您可以解析正则表达式中有限数量的嵌套,但这非常困难且不值得付出努力。使用自定义 python 函数更容易做到这一点。请参阅这个答案以获得很好的解释。

© www.soinside.com 2019 - 2024. All rights reserved.