Regex negation?

前端 未结 3 865
天涯浪人
天涯浪人 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:07

    Using the explanation here: https://stackoverflow.com/a/406408/584663

    I came up with: ^((?!((\w)(\w)\4\3)).)*$

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 01:26

    You can make it much shorter (and get more points) by simply using . and removing unnecessary parens:

    ^(?!.*(.)(.)\2\1)
    

    It just makes sure that there's no "abba" ("abba" here means 4 letters in that particular order we don't want to match) in any part of the string without having to match the whole word.

    0 讨论(0)
提交回复
热议问题