我遇到了如下的正则表达式:
foo(?!.*foo)
Run Code Online (Sandbox Code Playgroud)
如果它被喂食foo bar bar foo,它将找到最后一次出现的foo.我知道它使用了一种叫做负向前瞻的机制,这意味着它将匹配一个不以?后面的字符结尾的单词.!但这里的正则表达式如何运作?
来自sshashank的答案略有不同(因为containing他的答案中的单词对我来说不起作用,而且在正则表达式中你必须是迂腐的 - 这完全取决于精确度.)我100%肯定sshashank知道这一点并且只是为了简洁起见.
正则表达式匹配foo,未遵循(即负向前瞻(?!):
{{{任意数量的任何字符(即.*),然后是字符foo}}}
如果前瞻失败,则对应的部分.*不包含 foo.foo来晚了.
看到这个自动翻译:
NODE EXPLANATION
--------------------------------------------------------------------------------
foo 'foo'
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
foo 'foo'
--------------------------------------------------------------------------------
) end of look-ahead
Run Code Online (Sandbox Code Playgroud)
来自regex101的不同单词相同:
/foo(?!.*foo)/
Run Code Online (Sandbox Code Playgroud)foo matches the characters foo literally (case sensitive) (?!.*foo) Negative Lookahead - Assert that it is impossible to match the regex below .* matches any character (except newline) Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy] foo matches the characters foo literally (case sensitive)
RegexBuddy有什么要说的?
foo(?!.*foo)
Run Code Online (Sandbox Code Playgroud)
foo(?!.*foo)
.*
*foo