software
software

Reputation: 728

Canadian postal code regex?

In the postal code field only the following format should be valid.

B1C 2B3 or B1C3D3

how to write a regex for this?

Edited:

^([a-zA-Z]\d[a-zA-z]( )?\d[a-zA-Z]\d)$

This is my regex but it only accepting B1C C1B (notice space in between ) format. even with out space should be valid

Upvotes: 1

Views: 13455

Answers (3)

Arun Kumar S K
Arun Kumar S K

Reputation: 41

Use the below regex for Canadian ZIP code validations

^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$

Upvotes: 2

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

There are some real inconsistencies here. The Regex you provided ^([a-zA-Z]\d[a-zA-z]( )?\d[a-zA-Z]\d)$ matches what was stated by Scott regarding the correct Canadian format. However, the examples you provided do not follow the format B1C C1B or B1CC1B.

To add insult to injury, the Regex you provided works with the proper Canadian format. So there isn't any real reason to change it. I mean, I would change it to this ^([a-zA-Z]\d[a-zA-Z]\s?\d[a-zA-Z]\d)$ so that the single space isn't grouped, but that's just me.

However, as far as using it, it could be used in C# like this:

var matches = Regex.Match(inputString, @"^([a-zA-Z]\d[a-zA-Z]( )?\d[a-zA-Z]\d)$");
if (!matches.Success) {
    // do something because it didn't match
}

and now that it's been tagged with VB.NET:

Dim matches = Regex.Match(inputString, "^([a-zA-Z]\d[a-zA-Z]( )?\d[a-zA-Z]\d)$")
If Not matches.Success Then
    ' do something because it didn't match
End If

Upvotes: 4

Victor Zakharov
Victor Zakharov

Reputation: 26424

You'd want to validate the postal code against the address database. Not every postal code in the format A0A0A0 is a valid Canadian postal code. Examples of postal codes that do not exist:

Z0Z0Z0
Z9Z9Z9
Y7Y7Y7

Regarding preliminary checking, the easiest would probably be one with pre-processing of the value by VB.NET code. You need to remove spaces and convert to upper case. Then your regex is very simple: ([A-Z]\d){3}. And here is the full code for testing:

Imports System.Text.RegularExpressions

Module Module1
  Sub Main()
    Console.WriteLine(CanBeValidCanadianPostalCode("B1C 2B3")) 'prints True
    Console.WriteLine(CanBeValidCanadianPostalCode("B1C3D3")) 'prints True
  End Sub

  Private Function CanBeValidCanadianPostalCode(postal_code As String) As Boolean
    Return Regex.IsMatch(postal_code.Replace(" ", "").ToUpper, "([A-Z]\d){3}")
  End Function
End Module

Upvotes: 4

Related Questions