perl否定预测不匹配单词

时间:2014-10-09 06:47:12

标签: regex perl

我发现正则表达式不匹配此问题Regular expression to match a line that doesn't contain a word?中的单词。

u(?!i)会匹配一个单词,而不是i。答案说它检查每个角色是否没有跟着hede。因此,正则表达式不应该是/^(.(?!hede))*$/。它适用于包含hede但不是以它开头的单词。他们为什么使用/^((?!hede).)*$/。什么是点的位置之间的差异。我使用re=debug但仍然无法理解

2 个答案:

答案 0 :(得分:3)

(?!hede)表示向前看,看看是否有:hede。因此,hede之后有. (?!hede)之后是否有任何其他字符是有意义的。{/ 1}}是有效的正则表达式。

^((?!hede).)*$

的正则表达式解释
  ^                        the beginning of the string
  (                        group and capture to \1 (0 or more times):
    (?!                      look ahead to see if there is not:
      hede                     'hede'
    )                        end of look-ahead
    .                        any character except \n
  )*                       end of \1
  $                        before an optional \n, and the end of the string

使用(?<! 了解

^(.(?<!hede))*$

的模式说明
  ^                        the beginning of the string
  (                        group and capture to \1 (0 or more times):
    .                        any character except \n
    (?<!                     look behind to see if there is not:
      hede                     'hede'
    )                        end of look-behind
  )*                       end of \1
  $                        before an optional \n, and the end of the string

Lookahead and Lookbehind Zero-Length Assertions

下进行了更好的解释
  

它们不消耗字符串中的字符,但仅断言是否可以匹配

答案 1 :(得分:1)

`^((?!hede).)*$` means check for condtion ,then consume.

由于锚点,它不会包含任何包含hede的字符串。

参见演示。

http://regex101.com/r/iM2wF9/17

`^(.(?!hede))*$` means consume,then check for condition.

(这就是为什么从hede开始的单词传递的第一个字符是h并且它之前没有hede。所以这是一个传递