使用正则表达式按照特定模式提取多个字符串

use regex to extract multiple strings following certain pattern

我有一个像这样的长字符串,我想提取 Invalid items 之后的所有项目,所以我希望正则表达式 returns 像这样的列表 ['abc.def.com', 'bar123', 'hello', 'world', '1212', '5566', 'aaaa']

我试过使用这个模式,但它给我每场比赛一组

import re
test = 'Valid items: (aaa.com; bbb.com); Invalid items: (abc.def.com;); Valid items: (foo123;); Invalid items: (bar123;); Valid items: (1234; 5678; abcd;); Invalid items: (hello; world; 1212; 5566; aaaa;)'
re.findall(r'Invalid items: \((.+?);\)', test)
# ['abc.def.com', 'bar123', 'hello; world; 1212; 5566; aaaa']

有没有更好的方法使用正则表达式来做到这一点?

谢谢

如果您想 return 仅使用一个 findall 单独匹配所有匹配项,那么您需要使用正向后视,例如(?<=foo)。 Python 模块 re 不幸的是只支持固定宽度的 lookbehind。但是,如果您愿意使用出色的 regex 模块,那么就可以做到。

正则表达式:

(?<=Invalid items: \([^)]*)[^ ;)]+

示范: https://regex101.com/r/p90Z81/1

如果可以有空项目,对正则表达式的一个小修改允许捕获这些零宽度匹配项,如下所示:

(?<=Invalid items: \([^)]*)(?:[^ ;)]+|(?<=\(| ))

使用 re,您可以将匹配的组拆分为分号和 space

import re
test = 'Valid items: (aaa.com; bbb.com); Invalid items: (abc.def.com;); Valid items: (foo123;); Invalid items: (bar123;); Valid items: (1234; 5678; abcd;); Invalid items: (hello; world; 1212; 5566; aaaa;)'
results = []
for s in re.findall(r'Invalid items: \((.+?);\)', test):
     results = results + s.split(r"; ")

print(results)

输出

['abc.def.com', 'bar123', 'hello', 'world', '1212', '5566', 'aaaa']

看到一个Python demo