如何编写一个匹配所有字符序列的正则表达式而不用 'aaa'

How to write a regex which matches all char-sequences without 'aaa'

我试着用负面的前瞻来写,但是下面的正则表达式不起作用:

^.+(?!aaa).+$

它完全计算所有序列。如何修改?

您需要做的就是将 .* 添加到前瞻组

^(?!.*aaa).+$
  • (?!.*aaa) 否定前瞻确保字符串
  • 中没有aaa

Regex Demo

问题 ^.+(?!aaa).+$

  • . 将匹配字符串中的第一个字符。

  • (?!aaa) 检查第一个字符后面是否没有跟 aaa。显然这不是我们所期望的。相反,我们需要在整个字符串中搜索序列,而不是将搜索限制在第一个字符之后。

其中

  • (?!.*aaa) 将搜索扩展到整个字符串。
^(?:(?!aaa).)*$

您也可以尝试 this.See 演示。

https://regex101.com/r/xO3rH2/2

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (0 or more times
                       (matching the most amount possible)):
--------------------------------------------------------------------------------
    (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
      aaa                      'aaa'
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
    .                        any character except \n
--------------------------------------------------------------------------------
  )*                       end of grouping
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                       string