简体   繁体   中英

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

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

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: ([AZ]\\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

使用以下正则表达式进行加拿大邮政编码验证

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM