负面展望产生意想不到的结果
negative look ahead producing unexpected result
我期待的是一个空字符串,因为我特别否定了这个词
'authentication' 在我的字符串中。
string ='INFO 2013-09-17 12:13:44,487 authentication failed'
pattern = re.compile(r'\w+\s[\d-]+\s[\d:,]+\s(.*(?!authentication\s)failed)')
re.findall(pattern, string)
['authentication failed']
有人可以解释为什么会失败吗?
您的 .*
模式匹配 failed
之前的任何内容。 anything 本身不应后跟 authentication
加 1 个空白字符。这个限制很容易满足;在 'authentication '
.
之后没有带空格的 authentication
反转前瞻;改用负面回顾((?<!...)
)。如果 failed
前面没有紧跟 authentication
:
,则只匹配它
pattern = re.compile(r'\w+\s[\d-]+\s[\d:,]+\s(.*(?<!authentication\s)failed)')
现在文本不匹配; .*
无法匹配任何内容,因为其后没有有效的 failed
文本且前面也没有 authentication
.
我在 https://regex101.com/r/yGW7rH/1 放了一个演示;请注意,带有文本 matching failed
的第二行会导致匹配,而 authentication failed
不会。
我期待的是一个空字符串,因为我特别否定了这个词 'authentication' 在我的字符串中。
string ='INFO 2013-09-17 12:13:44,487 authentication failed'
pattern = re.compile(r'\w+\s[\d-]+\s[\d:,]+\s(.*(?!authentication\s)failed)')
re.findall(pattern, string)
['authentication failed']
有人可以解释为什么会失败吗?
您的 .*
模式匹配 failed
之前的任何内容。 anything 本身不应后跟 authentication
加 1 个空白字符。这个限制很容易满足;在 'authentication '
.
authentication
反转前瞻;改用负面回顾((?<!...)
)。如果 failed
前面没有紧跟 authentication
:
pattern = re.compile(r'\w+\s[\d-]+\s[\d:,]+\s(.*(?<!authentication\s)failed)')
现在文本不匹配; .*
无法匹配任何内容,因为其后没有有效的 failed
文本且前面也没有 authentication
.
我在 https://regex101.com/r/yGW7rH/1 放了一个演示;请注意,带有文本 matching failed
的第二行会导致匹配,而 authentication failed
不会。