使用正则表达式或标记化匹配出现在字符串中的两个单词的第一个出现同时考虑单词之间的距离5个单词

问题描述

我需要帮助匹配mystring中的两个单词“ hello”和“ hope”,但仅计算字符串中的第一个匹配项。他们彼此之间的最大距离是5个字。感谢任何帮助!

mystring = "hello bob nice weather hope you have a good day. hello jan hope weather is nice"

这是我到目前为止所拥有的。我希望结果只捕获第一次出现的“ hello”和“ hope”,然后停止匹配。

pattern = re.findall('\bhello(?:\W+\w+){0,5}\W+hope\b',mystring)

解决方法

我不知道如何使用RegEx在一行代码中进行操作,但是您可以使用regex进行部分处理,并使用列表推导来添加另一行代码。

mystring = "hello bob nice weather hope you have a good day. hello jan hope weather is nice"
pattern = re.findall('hello(?:\W+\w+){0,5}\W+hope',mystring)
pattern

['hello bob nice weather hope','hello jan hope']


new_pattern = [x for x in pattern if len(x.split()) == 5]
new_pattern

['hello bob nice weather hope']