首页 > 解决方案 > 正则表达式最小匹配

问题描述

我正在尝试在 Python 中编写一个正则表达式,它将匹配包含特定单词的单个句子(从.到)。.我写的正则表达式是r"\..*?hello.*?\.". 如您所见,我正在使用非贪婪量词。我匹配的文本是:

This is the 1st sentence. This is the 2nd. This is the 3rd, hello, world. This is the 4th.

(这里是regex101的链接)

我希望匹配为This is the 3rd, hello, world.,但尽管*?量词是非贪婪的,但匹配还包括第二句。我错过了什么?

标签: pythonregexregex-greedy

解决方案


推荐阅读