【问题标题】:use regex to extract multiple strings following certain pattern使用正则表达式按照特定模式提取多个字符串
【发布时间】:2026-01-03 12:20:02
【问题描述】:

我有一个像这样的长字符串,我想提取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']

有没有更好的方法来使用正则表达式?

谢谢

【问题讨论】:

    标签: python regex regex-group regex-greedy


    【解决方案1】:

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

    正则表达式:

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

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

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

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

    【讨论】:

      【解决方案2】:

      使用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)
      

      输出

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

      查看Python demo

      【讨论】:

        最近更新 更多