Numbers not of length 5

Viewed 36

I want to find potential US zip codes which are a string of 5 numbers, such as 12345 or 90210. The current regex I have uses alternation to get numbers of length 1-4 and then numbers of length 6+. Is there a better way to do this -- getting numbers of "all lengths except 5"?

1 Answers

You can use

^(?!\d{5}$)\d+$

See the regex demo and the regex graph:

enter image description here

Regex details:

  • ^ - start of string
  • (?!\d{5}$) - a negative lookahead that fails the match if there are any five digits immediately to the right of the current location till the end of string
  • \d+ - one or more digits
  • $ - end of string.

If the numbers are to be matched in a longer text as separate matches, you may consider using word, or digit, or even whitespace boundaries:

\b(?!\d{5}\b)\d+            // word boundaries
(?<!\d)(?!\d{5}(?!\d))\d+   // digit boundaries
(?<!\S)(?!\d{5}(?!\S))\d+   // whitespace boundaries
Related