我正在尝试用 Python 编写一个正则表达式,如果单词“required”或“mandatory”在任何一种方式的 10 个空格内,则匹配单词“attendance”。现在我的正则表达式看起来像这样:
re.compile(r'(attendance)\s(\w)\s(mandatory|required)')
这似乎只是匹配诸如“attendance is required”之类的句子,但是它不匹配诸如“attendance is important. We requires you come to class”之类的句子。知道如何编辑这个表达式吗?
请您参考如下方法:
您可以通过以下方式实现它:
(?: # attendance first, then require/required
\battendance\b\W+
(?:\w+\W+){0,10}
\brequired?\b
)
|
(?: # the other way round
\brequired?\b\W+
(?:\w+\W+){0,10}
\battendance\b
)
参见 a demo on regex101.com .
问题是,这需要一段时间才能成功,并且容易发生灾难性的回溯。
为了加快速度,您需要更新的
regex
module它支持原子分组 (
(?>...)
)。有了这个,只需要大约 600 步。考虑以下
Python
中的代码示例:
import regex as re
string = """
attendance word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 required
required word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 attendance
required word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 attendance (too far away)
"""
rx = re.compile(r"""
(?: # attendance first, then require/required
\battendance\b\W+
(?>\w+\W+){0,10}
\brequired?\b
)
|
(?: # the other way round
\brequired?\b\W+
(?>\w+\W+){0,10}
\battendance\b
)""", re.VERBOSE)
print(rx.findall(string))
对于非正则表达式的方式,也许看看ntlk
.