【问题标题】:Python - How to use re.finditer with multiple patternsPython - 如何使用具有多种模式的 re.finditer
【发布时间】:2019-12-08 16:49:51
【问题描述】:

我想在一个字符串中搜索 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

【问题讨论】:

  • 那你为什么要标记 findall?
  • 你试过什么?你能展示一下你的尝试吗?

标签: python regex python-3.x findall


【解决方案1】:

您可以从搜索词列表构建模式,然后使用 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']

【讨论】:

    【解决方案2】:

    这个想法是将pattern列表的条目组合成一个带有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']

    【讨论】:

    • 你的正则表达式也会匹配 'Margot' 中的 'got' 和 'Chad' 中的 'had'
    • 谢谢,我采纳了你的提示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多