如何在Python中使用Regex动态匹配整个单词

2024-10-03 13:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Regex,我想完全用Python匹配单词序列。 静态上是可能的,但我不知道动态匹配的方式。在

静态法

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

我正在尝试动态地做同样的事情,通过将整个序列与列表相匹配。
下面是代码片段:

^{pr2}$

它打印None作为输出。在

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


Tags: orimportresearch方式静态动态序列
3条回答

如果备选方法是选项,则可以将列表与列表进行比较:

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']

if any(word in 'When the loan amount is smaller than or equal to 50000' for word in list_less_than_or_equal):
  print("yep");
else:
  print("nope");

或正则表达式:

^{pr2}$

{可以使用字符串}代替连接。在

re.search(r'\b{0}\b'.format(word), ....)

你在第二个'\b'中忘了一个r。在

re.search(r'\b' + re.escape(word) + r'\b', ...)
#                                   ^

escape sequence ^{}在Python中有特殊的含义,它将变成\x08(U+0008)。看到\x08的正则表达式引擎将尝试匹配此文本字符,但失败。在

另外,我使用^{}来转义特殊的正则表达式字符,因此,例如,如果一个单词是"etc. and more",则点将按字面匹配,而不是匹配任何字符。在

相关问题 更多 >