Negative lookahead with capturing groups

人盡茶涼 提交于 2019-12-12 10:45:31

问题


I'm attempting this challenge:

https://regex.alf.nu/4

I want to match all strings that don't contain an ABBA pattern.

Match:

aesthophysiology
amphimictical
baruria
calomorphic

Don't Match

anallagmatic
bassarisk
chorioallantois
coccomyces
abba

Firstly, I have a regex to determine the ABBA pattern.

(\w)(\w)\2\1

Next I want to match strings that don't contain that pattern:

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

However this matches everything.

If I simplify this by specifying a literal for the negative lookahead:

^((?!agm).)*$

The the regex does not match the string "anallagmatic", which is the desired behaviour.

So it looks like the issue is with me using capturing groups and back-references within the negative lookahead.


回答1:


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

    ^^

You can use a lookahead here.See demo.The lookahead you created was correct but you need add .* so that it cannot appear anywhere in the string.

https://regex101.com/r/vV1wW6/39

Your approach will also work if you make the first group non capturing.

^(?:(?!(\w)(\w)\2\1).)*$

 ^^

See demo.It was not working because \2 \1 were different than what you intended.In your regex they should have been \3 and \2.

https://regex101.com/r/vV1wW6/40



来源:https://stackoverflow.com/questions/32862316/negative-lookahead-with-capturing-groups

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