负面前瞻是如何运作的

时间:2015-02-27 14:56:06

标签: regex

我想匹配一个不包含word&#34的字符串;" 以下解决方案对我来说是合乎逻辑的:

^(?!.*the.*).*$

以下一个(我在SO上遇到过)也有效,但我无法理解为什么会有效

^((?!the).)*$

在我看来(?!)。应该匹配a)任何b)单个字符然后重复*,所以正则表达式应匹配任何字符串? 有一个伟大的网站,我用作参考http://www.rexegg.com,但没有这样的例子

3 个答案:

答案 0 :(得分:1)

它基本上是匹配任意字符,并在每个位置搜索字符串文字“the”。如果找到,则否定取消匹配。

^            # Assert position at the beginning of a line (at beginning of the string or after a line break character)
(            # Match the regular expression below and capture its match into backreference number 1
   (?!          # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
      the          # Match the characters “the” literally
   )
   .            # Match any single character that is not a line break character
)*           # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$            # Assert position at the end of a line (at the end of the string or before a line break character)

答案 1 :(得分:0)

^((?!the).)*$

如果the前面有abcthe,这会在消费之前检查每个点。在c正则表达式引擎看到the之后,在字符串^$中它会显示但是因为你有$个锚点,因为引擎无法完全匹配它会失败并且不匹配任何内容。如果你移除abc它将匹配到{{1}}。

答案 2 :(得分:0)

上述解决方案有效,但前提是您还要匹配不包含字符the的字符串的字符串 - 例如,I was going there将被排除。如果要匹配不包含单词 the的所有内容,则需要单词边界:

^((?!\bthe\b).)*$

或:

^(?!.*\bthe\b).*$