正则表达式捕获短语,加上之前的词和之后的词

Regex capture phrase, plus word before and word after

使用 Python re,我试图在单个 return.

中捕获一个短语,加上之前的单词和之后的单词

即 从句子...
We want to see this phrase here and then again!
Return
see this phrase here

我得到的最接近的是...

>>> s = 'We want to see this phrase here and then again!'
>>> re.search("\w*\sthis phrase\w*\s",s)
<_sre.SRE_Match object; span=(11, 27), match='see this phrase '>

这看起来像是一个简单的错字。您的尝试寻找 this phrase 紧跟更多单词字符(因此 phrasesphraseology 也是),然后是 space , 但你说你想要它们的顺序相反。

"\w*\sthis phrase\s\w*"

对于“此短语前面没有 space”,这仍然无法正常工作。或“但是,不幸的是,这个短语被标点符号括起来了。”所以如果你想处理自由格式的文本,它可能还需要在设计上做更多的工作。

在您的正则表达式中,因为您在搜索词后匹配 \w*\s,所以它匹配 0 个词和搜索词后的一个空格。

您可以使用这个更强大的正则表达式来处理搜索词位于行首或行尾的情况:

(?:^|\w+\s+)this phrase(?:\s+\w+|$)

RegEx Demo

正则表达式详细信息:

  • (?:^|\w+\s+):匹配起始位置或一个单词后跟 1+ 个空格
  • this phrase:匹配搜索词
  • (?:\s+\w+|$):匹配结束位置或 1+ 空格后跟一个单词