One Regular Expression to validate US and Canada ZIP / Postal Code

ⅰ亾dé卋堺 提交于 2021-02-07 05:37:05

问题


I am developing a stationery program. Customers have choice to pick their region either US or Canada. When they enter address they have to enter ZIP/Postal code. I am trying to validate field but I cannot use reg exp either for US or Canada. I require a regular expression that validates for both country zip code.


回答1:


Not knowing what language you're using, I will not use any abbreviations for character classes:

^[0-9]{5}$|^[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]$

Depending on your language, you might be able to abbreviate this to

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

or

^(\d{5}|[A-Z]\d[A-Z] ?\d[A-Z]\d)$

To support ZIP+4:

^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] ?\d[A-Z]\d)$

And if you want to get really picky about your Canada codes:

^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$



回答2:


Furthering the answer above you could add (?i) to the beginning of the regex to make is case insensitive. So it would look like this:

^(?i)(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$


来源:https://stackoverflow.com/questions/22545097/one-regular-expression-to-validate-us-and-canada-zip-postal-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!