【发布时间】:2021-04-21 19:49:40
【问题描述】:
我需要匹配更大字符串中的模式not check。
bigger_string = '<some words and> do not check <some other words>'
但后面不应该有数字。所以,not check <some words> 应该匹配,但 not check 67 <some words> 不应该匹配。
我试过这些:
re.findall(re.compile(r'not\s*check\s*\D*', re.I), bigger_string)
re.findall(re.compile(r'not\s*check\s*[^0-9]*', re.I), bigger_string)
它不起作用。这总是返回一个匹配项。
【问题讨论】:
-
试试:
r'\bnot\s+check(?!\s*\d)' -
或
\bnot check\b[^\d\n]*$,如果在字符串结尾之前不应再有任何数字。 -
感谢@anubhava 和@the。我尝试了类似的模式
\s*(?!\d)。它也没有用。你的和我的有什么区别? -
使用 regex101.com 查看正则表达式是如何匹配的。
-
区别在于
\s*可以匹配一个零长度的字符串。所以它回溯并匹配not check,后跟零个空格。由于后面没有数字,因此模式匹配。
标签: python python-3.x regex