简体   繁体   中英

negative lookahead regex to not match a certain pattern

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!

You can use this reegx using a negative lookahead:

^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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM