In this Java regex tutorial, we will learn to use a regular expression to validate Canadian postal zip codes. You can modify the regex to suit it for any other format as well.
1. What is a Valid Canadian Postal Code?
A Canadian postal code is a six-character string.
A valid Canadian postcode is –
- in the format
A1A 1A1
, whereA
is a letter and1
is a digit. - a space separates the third and fourth characters.
- do not include the letters D, F, I, O, Q or U.
- the first position does not make use of the letters W or Z.
2. Regex for Canadian Postal Code
^(?!.*[DFIOQU])[A-VXY][0-9][A-Z] ?[0-9][A-Z][0-9]$
- In the above regex, the negative lookahead at the beginning of this regular expression prevents D, F, I, O, Q, or U anywhere in the subject string.
- The <[A-VXY]> character class further prevents W or Z as the first character.
3. Example
List<String> zips = new ArrayList<String>();
//Valid ZIP codes
zips.add("K1A 0B1");
zips.add("B1Z 0B9");
//Invalid ZIP codes
zips.add("K1A 0D1");
zips.add("W1A 0B1");
zips.add("Z1A 0B1");
String regex = "^(?!.*[DFIOQU])[A-VXY][0-9][A-Z] ?[0-9][A-Z][0-9]$";
Pattern pattern = Pattern.compile(regex);
for (String zip : zips)
{
Matcher matcher = pattern.matcher(zip);
System.out.println(matcher.matches());
}
true
true
false
false
That was pretty easy, right?
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Thx that was what im looking for.