python - 查找单词的所有出现 + 子字符串
问题描述
我有“主要”词“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)
解决方案
如果您不需要使用正则表达式,则可以使用 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)
请注意,即使使用此循环,如果您使用 |,您也需要让较长的单词出现在较短的单词之前。正则表达式中的运算符。这是因为 | 永远不会贪婪,并且会匹配第一个单词,而不是最长的单词。
推荐阅读
- c++ - OpenCV C ++中透视变换中的图像保留
- javascript - 如何增加标题右列的宽度
- python - 使用 Scrapy,返回的 HTML 文件在目录中被涂黑并打开 404 错误。知道为什么吗?
- r - 为什么汇总的四分位数与手动计算的四分位数不同?
- c# - 创建 Dynamics CRM 插件以执行外部任务
- docker - 将 Gitlab Secrets 传递给 CI 中的 docker build
- haskell - 在 haskell 中使用替代前奏
- google-apps-script - 动态查询函数
- python - TypeError:关键字必须是字符串
- jquery - 使用元素的属性值查找相关元素