Skip to content
Advertisement

Negative lookahead RegEx limited to an exact number of characters

How can I limit a negative lookahead RegEx to an exact number of characters?

For example, this sentence should be denied…

This car is not that fast!

while this one should be allowed…

The car you are about to see may not be that fast, but it's very beautiful!

The RegEx should match any sentence that contains the word ‘car’, except the ones that include the word ‘not’ in the following 10 characters. This is the case of the first sentence, where there are only 4 characters in between the ‘car’ and ‘not’ words. So this sentence should be denied.

The second sentence, however, has more than 10 characters in between the ‘car’ and ‘not’ words, so it should pass the RegEx negative assertion.

Basically, what I am looking for is a negative lookahead RegEx that is limited to a certain number of characters.

Advertisement

Answer

Indeed, you can use negative look-ahead:

.*?car(?!.{0,10}not).*

If “car” and “not” in this rule are supposed to be separate words and not just substrings of any sequence, then add the appropriate b:

.*?bcarb(?!.{0,10}bnotb).*

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement