捕获组的负向超前 [英] Negative lookahead with capturing groups

查看:74
本文介绍了捕获组的负向超前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试挑战:

https: //regex.alf.nu/4

我要匹配所有不包含ABBA模式的字符串。

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

匹配项:

aesthophysiology
amphimictical
baruria
calomorphic

不匹配

anallagmatic
bassarisk
chorioallantois
coccomyces
abba

首先,我有一个正则表达式来确定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).)*$

但是,这一切都匹配。

如果我通过为负前瞻指定文字来简化此操作:

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

^((?!agm).)*$

egex与所需的行为 anallagmatic字符串不匹配。

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.

推荐答案

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

    ^^

您可以使用此处为 lookahead 。请参见演示。您创建的lookahead是正确的,但您需要添加。* ,这样它才不会出现

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

如果您使第一组不被捕获

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

 ^^

请参阅演示。之所以不起作用,是因为 \2 \1 与您的预期有所不同。在正则表达式中,它们应该是 \3 \2

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

这篇关于捕获组的负向超前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆