Java Reference
In-Depth Information
U.S. ZIP codes and UK postcodes. If you needed to check for other countries, the code would need
modifying. You may find that checking more than one or two postal codes in one regular expression
begins to get unmanageable, and it may well be easier to have an individual regular expression for
each country's postal code you need to check. For this purpose though, let's combine the regular
expression for the United Kingdom and the United States:
^(\d{5}(-\d{4})?|[a-z][a-z]?\d\d? ?\d[a-z][a-z])$
This is actually in two parts. The first part checks for ZIP codes, and the second part checks for UK
postcodes. Start by looking at the ZIP code part.
ZIP codes can be represented in one of two formats: as five digits (12345), or five digits followed
by a dash and four digits (12345‐1234). The ZIP code regular expression to match these is as
follows:
\d{5}(-\d{4})?
This matches five digits, followed by an optional non‐capturing group that matches a dash, followed
by four digits.
For a regular expression that covers UK postcodes, let's consider their various formats.
UK postcode formats are one or two letters followed by either one or two digits, followed
by an optional space, followed by a digit, and then two letters. Additionally, some central
London postcodes look like SE2V 3ER, with a letter at the end of the first part. Currently,
only some of those postcodes start with SE, WC, and W, but that may change. Valid
examples of UK postcodes include: CH3 9DR, PR29 1XX, M27 1AE, WC1V 2ER, and
C27 3AH.
Based on this, the required pattern is as follows:
([a-z][a-z]?\d\d?|[a-z]{2}\d[a-z]) ?\d[a-z][a-z]
These two patterns are combined using the | character to “match one or the other” and grouped
using parentheses. You then add the ^ character at the start and the $ character at the end of the
pattern to be sure that the only information in the string is the postal code. Although postal codes
should be uppercase, it is still valid for them to be lowercase, so you also set the case‐insensitive
option as follows when you use the regular expression:
^(\d{5}(-\d{4})?|([a-z][a-z]?\d\d?|[a-z{2}\d[a-z]) ?\d[a-z][a-z])$
Just for reference, let's look once again at the isValidPostalCode() function:
function isValidPostalCode(postalCode) {
var pcodeRegExp = /^(\d{5}(-\d{4})?|([a-z][a-z]?\d\d?|[a-z{2}\d[a-z])
?\d[a-z][a-z])$/i;
return pcodeRegExp.test( postalCode );
}
Again, remember that the regular expression must be on one line in your code.
Search WWH ::




Custom Search