python - 使用正则表达式、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]
。
如何修改正则表达式以给我所有+
介于[
和之间的括号标签]
?谢谢。
解决方案
您需要使您的正则表达式不贪婪,如下所示:
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]
推荐阅读
- fonts - 如何在 PIL 中设置字体?
- python-3.x - fastai 中的 LMDataLoader
- android - 如果有动画小部件,Flutter 不会重建
- julia - 如何在 Julia 中使用提升规则?
- java - 我需要帮助解释这意味着什么 res += (char) ((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
- angular - 使用其类型映射 Angular HttpClient 错误
- c# - 插入双精度时遇到问题,例如 4.8(例如)(C#)
- python - 当用户输入输入时如何从for循环中打印输出
- azure - 无法使用颤振的 SAS 令牌上传到 Azure 存储
- python - 如何传递要在 Pyside2 中调用的函数?