首页 > 解决方案 > 使用正则表达式、Python 3 捕获多个括号内的序列

问题描述

我正在使用 Python 3 并使用带有括号标签的标题字符串,其中一对名称由+. 像这样:[John+Alice] A title here.

我一直在使用正则表达式re.search('\[(.+)\]', title)来获取 tag [John+Alice],这很好,但是在遇到带有多个括号标签的标题时会出现问题:

[John+Alice] [Hayley + Serene] Another title.

这给了我[John+Alice] [Hayley + Serene],当我更喜欢[John+Alice][Hayley + Serene]

如何修改正则表达式以给我所有+介于[和之间的括号标签]?谢谢。

标签: pythonregexpython-3.x

解决方案


您需要使您的正则表达式不贪婪,如下所示:

title = '[John+Alice] [Hayley + Serene] Another title.'

for t in re.findall('\[(.+?)\]', title):
    print(t)

输出

John+Alice
Hayley + Serene

如果必须包含括号,请使用finditer

for t in re.finditer('\[(.+?)\]', title):
    print(t.group())

输出

[John+Alice]
[Hayley + Serene]

非贪婪限定符,例如*?, +?, ??匹配尽可能少的文本。你可以在这里找到更多关于贪婪与非贪婪的信息。

观察

在您提到的问题中,您正在使用'\[(.+)\]'匹配所有+介于[and之间的括号标签],但实际上它的作用远不止于此。例如,对于以下示例:

title = '[John+Alice] [Hayley + Serene] [No plus text] Another title.'
re.search('\[(.+)\]', title)

返回:

[John+Alice] [Hayley + Serene] [No plus text]

因此,我的修改(使用finditer)给出:

[John+Alice]
[Hayley + Serene]
[No plus text]

因此[No plus text]是不正确的,要修复你应该使用类似的东西:

title = '[John+Alice] [Hayley + Serene] [No plus text] Another title.'

for t in re.finditer('\[(.+?\+.+?)?\]', title):
    print(t.group())

输出

[John+Alice]
[Hayley + Serene]

推荐阅读