Skip to main content
 首页 » 编程设计

Python 正则表达式查找两个子字符串之间的所有字符串

2024年09月07日23bluestorm

我希望找到两个子字符串之间的所有字符串,同时保留第一个子字符串并丢弃第二个子字符串。不过,子字符串可能是几个值之一。例如,如果这些是可能的子字符串:

subs = ['MIKE','WILL','TOM','DAVID'] 

我正在寻找这样的字符串:

Input: 
 
text = 'MIKE an entry for mike WILL and here is wills text DAVID and this belongs to david' 
 
Output: 
 
[('MIKE': 'an entry for mike'), 
 ('WILL': 'and here is wills text'), 
 ('DAVID': 'and this belongs to david')] 

尾随空格并不重要。我试过:

re.findall('(MIKE|WILL|TOM|DAVID)(.*?)(MIKE|WILL|TOM|DAVID)',text) 

仅返回第一次出现并保留结束子字符串。不太确定最佳方法。

请您参考如下方法:

你可以使用

import re 
text = 'MIKE an entry for mike WILL and here is wills text DAVID and this belongs to david' 
subs = ['MIKE','WILL','TOM','DAVID'] 
res = re.findall(r'({0})\s*(.*?)(?=\s*(?:{0}|$))'.format("|".join(subs)), text) 
print(res) 
# => [('MIKE', 'an entry for mike'), ('WILL', 'and here is wills text'), ('DAVID', 'and this belongs to david')] 

参见 Python demo .

动态构建的模式看起来像(MIKE|WILL|TOM|DAVID)\s*(.*?)(?=\s*(?:MIKE|WILL|TOM|DAVID|$))。在这种情况下。

详情

  • (MIKE|WILL|TOM|DAVID) - 第 1 组匹配备选子字符串之一
  • \s* - 0+ 个空格
  • (.*?) - 第 2 组捕获除换行符以外的任何 0+ 个字符(使用 re.S 标志匹配任何字符),最少可能,直到第一个...
  • (?=\s*(?:MIKE|WILL|TOM|DAVID|$)) - 0+ 个空格后跟一个子字符串或字符串结尾 ($)。这些文本不会被消耗,因此,正则表达式引擎仍然可以获得后续匹配。