我遇到了如下的正则表达式:
foo(?!.*foo)
如果它被喂食
foo bar bar foo
,它将找到最后一次出现的 foo。我知道它使用一种称为负前瞻的机制,这意味着它将匹配一个不以 ?! 后的字符结尾的单词。但是这里的正则表达式是如何工作的?
最佳答案
与 sshashank 的答案略有不同(因为他的回答中的 containing
一词对我不起作用,而在正则表达式中,您必须迂腐——这完全是关于精度。)我 100% 确定 sshashank 知道这一点,并且只将其表述为为简洁起见。
正则表达式匹配 foo
, 不遵循(即负前瞻 (?!
):
{{{任意数量的任何字符(即 .*
)然后字符 foo
}}}
如果前瞻失败,则对应于 .*
的部分不包含 foo
. foo
稍后来。
看到这个 automatic translation :
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
来自 regex101 的不同词相同:
/foo(?!.*foo)/
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)
foo(?!.*foo)
foo
(?!.*foo)
.*
*
foo
关于regex - 当找到最后一次出现的单词时,这个正则表达式是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23751058/