calylac
calylac

Reputation: 19

Regex to check for any number of 4 or more digits EXCEPT specific numbes

a client is asking for a regex to check for any number higher than 999 to remind to add a thousand separator e.g. 1,000, however they don't want to get false positives for commonly mentioned years (2019, 2020, 2021) etc. Is there any way to achieve this, i.e. "any number of 4 or more digits EXCEPT these specific numbers"?

I've considered the below, but this will ignore any number where the first digit is 2, so will miss out anything between 2000-2999 as well as 20,000, 2,000,000 etc., which definitely need to have thousand separators added.

[1|3-9]\d{3,}

Is this something that can actually be done with a regex? Thanks in advance!

Upvotes: 0

Views: 40

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

Using [1|3-9]\d{3,} will not match 2, but will also give you a partial match in 21234

Note that you can omit the | as it would match it literally in the character class.


Before matching 4 or more digits, if supported, you can assert using a negative lookahead that what is directly to the right is not 2019, 2020 or 2021

At the beginning you can add a word boundary or for example an anchor ^ to assert the start of the string.

\b(?!20(?:2[01]|19)\b)\d{4,}

Regex demo

Upvotes: 1

Related Questions