[英]Canadian postal code regex?
In the postal code field only the following format should be valid. 在邮政编码字段中,仅以下格式有效。
B1C 2B3 or B1C3D3 B1C 2B3或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. 这是我的正则表达式,但它仅接受B1C C1B(之间的注意空格)格式。 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. 您提供的正则表达式
^([a-zA-Z]\\d[a-zA-z]( )?\\d[a-zA-Z]\\d)$
与Scott所说的正确的加拿大格式相符。 However, the examples you provided do not follow the format B1C C1B or B1CC1B
. 但是,您提供的示例未遵循
B1C C1B or B1CC1B
格式。
To add insult to injury, the Regex you provided works with the proper Canadian format. 为了增加侮辱性伤害,您提供的Regex使用正确的加拿大格式。 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. 我的意思是,我将其更改为
^([a-zA-Z]\\d[a-zA-Z]\\s?\\d[a-zA-Z]\\d)$
以便单个空格为'没分组,但那只是我。
However, as far as using it, it could be used in C# like this: 但是,就其用途而言,它可以像这样在C#中使用:
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: 现在,它已被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. 并非每个
A0A0A0
格式的A0A0A0
都是有效的加拿大邮政编码。 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. 关于初步检查,最简单的方法可能是使用VB.NET代码对值进行预处理。 You need to remove spaces and convert to upper case.
您需要删除空格并转换为大写。 Then your regex is very simple:
([AZ]\\d){3}
. 那么您的正则表达式非常简单:
([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}$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.