Regex negation?

岁酱吖の 提交于 2019-11-30 17:54:30

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.

Bill

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

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

inquist

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!