首页 > 解决方案 > 查找单词的所有出现 + 子字符串

问题描述

我有“主要”词“LAUNCHER”和另外两个词“LAUNCH”和“LAUNCHER”。我想找出(使用正则表达式),哪些词在“主要”词中。我正在使用 findAll,正则表达式: "(LAUNCH)|(LAUNCHER)" ,但这只会返回 LAUNCH 而不是它们两者。我该如何解决?

import re
mainword = "launcher"
words = "(launch|launcher)"
matches = re.findall(words,mainword)
for match in matches:
  print(match)

标签: pythonregex

解决方案


如果您不需要使用正则表达式,则可以使用 IN 运算符和简单的循环或列表推导更有效地完成此操作:

mainWord = "launcher"
words    = ["launch","launcher"]
matches  = [ word for word in words if word in mainWord ] 

# case insensitive...
matchWord = mainWord.lower()
matches   = [ word for word in words if word.lower() in matchWord ]

即使您确实需要正则表达式,也需要一个循环,因为 re.findAll() 从不匹配重叠模式:

import re
pattern   = re.compile("launcher|launch")
mainWord  = "launcher"
matches   = []
startPos  = 0
lastMatch = None
while startPos < len(mainWord):
    if lastMatch : match = pattern.match(mainWord,lastMatch.start(),lastMatch.end()-1) 
    else         : match = pattern.match(mainWord,startPos)
    if not match: 
        if not lastMatch : break
        startPos  = lastMatch.start() + 1
        lastMatch = None
        continue
    matches.append(mainWord[match.start():match.end()])
    lastMatch = match

print(matches)

请注意,即使使用此循环,如果您使用 |,您也需要让较长的单词出现在较短的单词之前。正则表达式中的运算符。这是因为 | 永远不会贪婪,并且会匹配第一个单词,而不是最长的单词。


推荐阅读