Skip to main content
 首页 » 编程设计

python之正则表达式捕获一组的多个重复

2024年08月23日36emanlee

我有一个示例文本:

Lorem ipsum AB-CD-01 dolor sit amet, AB-CD-Foobar consectetur 

我想捕获所有短语 AB-CD-*。我正在尝试这样的事情:

pattern = re.compile("((AB-CD-\S+).*)*") 
result = pattern.search(text) 
print(result.groups()) # expected: ('AB-CD-01', 'AB-CD-Foobar') 

我知道这是一个相当简单和基本的正则表达式问题,但我找不到任何好的解决方案。

请您参考如下方法:

您可以使用更简单的模式 re.findall :

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

带有更新的正则表达式的示例代码:

import re 
p = re.compile(r'AB-CD-\S+') 
test_str = "Lorem ipsum AB-CD-01 dolor sit amet, AB-CD-Foobar consectetur" 
print(re.findall(p, test_str)) 
# => ['AB-CD-01', 'AB-CD-Foobar'] 

参见 IDEONE和 regex demo

re.search只找到第一个匹配项,re.findall 返回匹配列表(如果模式中没有定义捕获组 - 这就是我建议删除它们的原因)。