负向前瞻性正则表达式与某种模式不匹配

时间:2022-06-15 15:20:16

I am trying to not match a string if it contains four dots or more in a row. This is my current regex.

我试图不匹配一个字符串,如果它连续包含四个点或更多。这是我现在的正则表达式。

^(\s*(CODE)\s?([0-9]{1,2}))(.(?!\.\.\.\.*))*$

So, my regex should match

所以,我的正则表达式应该匹配

CODE 7 Newton 

But it should NOT match

但它不应该匹配

CODE 7 Newton ....................

What am I doing wrong? It is matching all the dots even with a negative look ahead!

我究竟做错了什么?它与所有的点匹配,即使是前方的负面看!

1 个解决方案

#1


2  

You can use this reegx using a negative lookahead:

您可以使用负前瞻使用此reegx:

^CODE\s+\d+(?!.*\.{4})

RegEx Demo

(?!.*\.{4}) is negative lookahead that asserts (without matching) that we don't have 4 DOTs ahead of current position.

(?!。* \。{4})是否定前瞻,断言(不匹配)我们在当前位置之前没有4个DOT。

PS: .* is greedy and does consume all the text till end whole asserting but it lets regex engine backtrack 4 positions back to match 4 dots at the end of the match.

PS:。*是贪婪的并且消耗所有文本直到结束整个断言但它让正则表达式引擎回溯4个位置以匹配比赛结束时的4个点。

#1


2  

You can use this reegx using a negative lookahead:

您可以使用负前瞻使用此reegx:

^CODE\s+\d+(?!.*\.{4})

RegEx Demo

(?!.*\.{4}) is negative lookahead that asserts (without matching) that we don't have 4 DOTs ahead of current position.

(?!。* \。{4})是否定前瞻,断言(不匹配)我们在当前位置之前没有4个DOT。

PS: .* is greedy and does consume all the text till end whole asserting but it lets regex engine backtrack 4 positions back to match 4 dots at the end of the match.

PS:。*是贪婪的并且消耗所有文本直到结束整个断言但它让正则表达式引擎回溯4个位置以匹配比赛结束时的4个点。