繁体   English   中英

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

[英]use regex to extract multiple strings following certain pattern

我有一个像这样的长字符串,我想提取Invalid items之后的所有项目,所以我希望正则表达式返回一个列表,如['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']

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

谢谢

如果您想仅使用一个findall单独返回所有匹配项,那么您需要使用积极的后视,例如(?<=foo) 不幸的是, re模块仅支持固定宽度的后视。 但是,如果您愿意使用出色的正则表达式模块,那么它可以完成。

正则表达式:

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

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

如果可能有空项,则对正则表达式稍作修改即可捕获这些零宽度匹配项,如下所示:

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

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

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)

Output

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

请参阅Python 演示

这将仅选择有效或无效中提到的所需模式

import re
test = 'Valid items: (abc.h; bac.h); Invalid items: (aaa.123;); Valid items: (aaa H;bbbb H;); Invalid items: (abc;bac;)'
results = []
for s in re.findall(r'Invalid items: \((.+?);\)', test):
     results = results + s.split(r" ; ")
 
print(results)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM