查找单词的最后一次出现时,此正则表达式如何工作?

pho*_*sis 7 regex

我遇到了如下的正则表达式:

foo(?!.*foo)
Run Code Online (Sandbox Code Playgroud)

如果它被喂食foo bar bar foo,它将找到最后一次出现的foo.我知道它使用了一种叫做负向前瞻的机制,这意味着它将匹配一个不以?后面的字符结尾的单词.!但这里的正则表达式如何运作?

zx8*_*x81 9

来自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)/

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)
Run Code Online (Sandbox Code Playgroud)

RegexBuddy有什么要说的?

富(?!.*FOO)

foo(?!.*foo)
Run Code Online (Sandbox Code Playgroud)
  • 字面匹配字符串"foo"(区分大小写) foo
  • 断言从这个位置开始不可能匹配下面的正则表达式(负向前瞻) (?!.*foo)
    • 匹配任何不是换行符的单个字符(换行符,回车符,下一行,行分隔符,段落分隔符) .*
      • 在零和无限次之间,尽可能多次,根据需要回馈(贪婪) *
    • 字面匹配字符串"foo"(区分大小写) foo


ssh*_*124 5

foo仅当( ) 后面没有?!包含任何其他文本 ( .*)时,它才匹配foo