如何在 Python 中使用正则表达式动态匹配整个单词

Use*_*898 0 python regex string-matching

使用正则表达式,我想完全在 Python 中匹配一系列单词。静态是可能的,但我不知道动态匹配方式。

静态方法

import re
print(re.search(r'\bsmaller than or equal\b', 'When the loan amount is smaller than or equal to 50000'))
Run Code Online (Sandbox Code Playgroud)

我试图通过将整个序列与列表匹配来动态地做同样的事情。
这是下面的代码片段:

import re
list_less_than_or_equal = ['less than or equal', 'lesser than or equal', 'lower than or equal', 'smaller than or equal','less than or equals', 'lesser than or equals', 'lower than or equals', 'smaller than or equals', 'less than equal', 'lesser than equal', 'higher than equal','less than equals', 'lesser than equals', 'higher than equals']

for word in list_less_than_or_equal:
    print(re.search(r'\b'+word+'\b', 'When the loan amount is smaller than or equal to 50000'))
Run Code Online (Sandbox Code Playgroud)

它打印None为输出。

如何动态匹配整个单词序列?

ken*_*ytm 6

r第二次忘记了'\b'

re.search(r'\b' + re.escape(word) + r'\b', ...)
#                                   ^
Run Code Online (Sandbox Code Playgroud)

转义序列\b具有特殊的意义在Python,将成为\x08(U + 0008)。正则表达式引擎\x08将尝试匹配此文字字符并失败。

另外,我曾经re.escape(word)对特殊的正则表达式字符进行转义,因此例如,如果一个单词是"etc. and more"点,则将按字面匹配,而不是匹配任何字符。