Regex negation?

前端 未结 3 881
天涯浪人
天涯浪人 2021-01-04 00:29

I\'m playing Regex Golf (http://regex.alf.nu/) and I\'m doing the Abba hole. I have the following regex that matches the wrong side entirely (which is what I was trying to

3条回答
  •  暖寄归人
    2021-01-04 01:11

    The key here turns out to be the leading caret, ^, and the .*

    (?! ...) is a look-ahead construct, and so does not advance the regex processing engine.

    /(?! ...)/ on its own will correctly return a negative result for items matching the expression within; but for items which do not match (...) the regex engine continues processing. However if your regex only contains the (?! ) there is nothing left to process, and the regex processing position never advances. (See this great answer).

    Apparently since the remaining regex is empty, it matches any zero-width segment of a string, i.e. it matches any string.

    [begin SWAG]

    With the caret ^ present, the regex engine is able to recognize that you are looking for a real answer and that you do not want it to tell you the string contains zero-width components.

    [end SWAG]

    Thus it is able to correctly fail to match when the (?! ) succeeds.

提交回复
热议问题