-1

I'm using this regex to match for zip codes, but it's also matching for 00000 and plus 4. I've been looking into and not topics for regex but have bee

^\d{5}(?:[-\s]\d{4})?$

Croisade
  • 225
  • 2
  • 12
  • Can you add some example of valid and invalid matches? – The fourth bird Jul 29 '21 at 13:30
  • 1
    You can disallow five zeros with `^(?!0{5}$)\d{5}(?:[-\s]\d{4})?$`, but what is the problem with `+4`? The regex you have can't match it. – Wiktor Stribiżew Jul 29 '21 at 13:30
  • @WiktorStribiżew The "plus 4" in the context of a US postal code refers to the e.g. `-1234` which may immediately follow the 5 digit ZIP code. These 4 digits sometimes correspond to a physical PO box. – Tim Biegeleisen Jul 29 '21 at 13:40

2 Answers2

3

Try this :

^(?!00000)\d{5}(?:[-\s]\d{4})?$

Regex explanation

Sanket Shah
  • 2,888
  • 1
  • 11
  • 22
0

You could use a negative lookahead to assert that the ZIP code is not 00000:

^(?!00000\b)\d{5}(?:[-\s]\d{4})?$
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360