Python - 如何使用具有多种模式的 re.finditer



我想在字符串中搜索 3 个单词并将它们放在列表中 像这样:

sentence = "Tom once got a bike which he had left outside in the rain so it got rusty"

pattern = ['had', 'which', 'got' ]

答案应该是这样的:['got', 'which','had','got']我还没有找到以这种方式使用re.finditer的方法。可悲的是,我需要使用finditer而是findall

您可以从搜索的单词列表中构建模式,然后使用finditer返回的匹配项的列表理解来构建输出列表:

import re
sentence = "Tom once got a bike which he had left outside in the rain so it got rusty"
pattern = ['had', 'which', 'got' ]
regex = re.compile(r'b(' + '|'.join(pattern) + r')b')
# the regex will be r'b(had|which|got)b'
out = [m.group() for m in regex.finditer(sentence)]
print(out)
# ['got', 'which', 'had', 'got']

这个想法是将模式列表的条目组合在一起,形成一个带有 or s 的正则表达式。 然后,您可以使用以下代码片段:

import re
sentence = 'Tom once got a bike which he had left outside in the rain so it got rusty. ' 
'Luckily, Margot and Chad saved money for him to buy a new one.'
pattern = ['had', 'which', 'got']
regex = re.compile(r'b({})b'.format('|'.join(pattern)))
# regex = re.compile(r'b(had|which|got)b')
results = [match.group(1) for match in regex.finditer(sentence)]
print(results)

结果是['got', 'which', 'had', 'got'].

相关内容

  • 没有找到相关文章

最新更新