【发布时间】:2021-12-23 10:52:19
【问题描述】:
我想在我的正则表达式查询中匹配特定单词之前和之后包含 5 个字符。这些词在一个列表中,我对其进行迭代。
请看下面的例子,这是我尝试过的:
import re
text = "This is an example of quality and this is true."
words = ['example', 'quality']
words_around = []
for word in words:
neighbors = re.findall(fr'(.{0,5}{word}.{0,5})', str(text))
words_around.append(neighbors)
print(words_around)
输出为空。我希望一个数组包含['s an exmaple of q', 'e of quality and ']
【问题讨论】:
-
看起来 PyPi 正则表达式模块在这里很方便,因为您需要特定的重叠匹配。
-
当然。我编辑了我的帖子以将其包含在我的示例中。