I'm looking for the ultimate postal code and zip code regex. I'm looking for something that will cover most (hopefully all) of the world.
相关问题
- Improve converting string to readable urls
- Regex to match charset
- Regex subsequence matching
- Accommodate two types of quotes in a regex
- Set together letters and numbers that are ordinal
相关文章
- Optimization techniques for backtracking regex imp
- Regex to check for new line
- Allow only 2 decimal points entry to a textbox usi
- Comparing speed of non-matching regexp
- Regular expression to get URL in string swift with
- 请问如何删除之前和之后的非字母中文单字
- Lazy (ungreedy) matching multiple groups using reg
- when [:punct:] is too much [duplicate]
Depending on your application, you might want to implement regex matching for the countries where most of your visitors originate and no validation for the rest (accept anything).
Given that there are so many edge cases for each country (eg. London addresses may use a slightly different format to the rest of the UK) I don't think that there is an ultimate regex other than maybe:
Best of going with a fairly broad pattern (well not quite as broad as the above), or treat each country/region with a specific pattern of its own!
UPDATE: However, it may be possible to dynamically construct a regex based upon lots of smaller, region specific rules - not sure about performance though!
Lots of country specific patterns can be found on the RegExLib site.
We use the following:
Canada
America
Other
Trying to cover the whole world with one regular expression is not completely possible, and certainly not feasible or recommended.
Not to toot my own horn, but I've written some pretty thorough regular expressions which you may find helpful.
Canadian postal codes
US ZIP codes
UK post codes
It is not possible to guarantee accuracy without actually mailing something to an address and having the person let you know when they receive it, but we can narrow things by down by eliminating cases that we know are bad.
Every postal code system uses only A-Z and/or 0-9 and sometimes space/dash
Not every country uses postal codes (ex. Ireland outside of Dublin), but we'll ignore that here.
The shortest postal code format is Sierra Leone with
NN
The longest is American Samoa with
NNNNN-NNNNNN
You should allow one space or dash.
Should not begin or end with space or dash
This should cover the above:
The problem is going to be that you probably have no good means of keeping up with the changing postal code requirements of countries on the other side of the globe and which you share no common languages. Unless you have a large enough budget to track this, you are almost certainly better off giving the responsibility of validating addresses to google or yahoo.
Both companies provide address lookup facuilities through a programmable API.