0

I need to create a regular expression for a Canadian and US postal code but the zip code has to start at 10000 and go to 99999, I've tried various configurations but it won't work for the zip code starting at 10000, not sure what I'm doing wrong. Any help would be appreciated.

'^[A-Z][0-9][A-Z]-[0-9][A-Z][0-9]$|(^[1-9]{5}(?[0-9]{4})?$)'

obb-taurus
  • 847
  • 1
  • 7
  • 12
  • Are you only interested in answers from people who already know which "codes" are valid for US/Canada and which aren't? If you want people from Japan and Russia to help you, please describe in full detail what are the rules: which strings are valid postal codes for those two countries. –  Sep 21 '17 at 23:36
  • 1
    Also: US postal codes may begin with 0 (many states in the North-East). –  Sep 22 '17 at 00:25

2 Answers2

2

You have [1-9]{5} which will only accept zip codes starting with five non-zero digit characters. 10000 has zeroes so does not match the pattern. What you want is, given you requirement of a leading non-zero digit, to match [1-9] for a single character and then [0-9] (or \d) for the next 4 characters:

US:

^[1-9]\d{4}([ -]?\d{4})?$

Canadian:

^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][ -]?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$

Both together:

^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][ -]?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$|^[1-9]\d{4}([ -]\d{4})?$
MT0
  • 143,790
  • 11
  • 59
  • 117
1

You wrote

[1-9]{5}(?[0-9]{4})?

The question marks weren't helping you.

Boston, and lots of other places, have well-formed ZIPs starting with zero. But assuming you really want to exclude them, then just insist on proper initial digit followed by four more unrestricted digits:

[1-9][0-9]{4}

(Notice that ZIP+4 appears to be beyond the scope of the problem statement.)

J_H
  • 17,926
  • 4
  • 24
  • 44