多个国家RegEx检查器

g0czyy6m  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(100)

有人可以帮助我如何改变下面的功能,使它可以采取多种模式的基础上,国家代码是沿着邮政编码输入?

Function Checker(Myrange As Range) As String
    Dim RegEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim strOutput As String
    
    
    strPattern = "^[1-9]\d{3}$"
    If strPattern <> "" Then
        strInput = Myrange
        strReplace = ("Matched")
        
        With RegEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With
        
        If RegEx.Test(strInput) Then
           Checker = RegEx.Replace(strInput, strReplace)
        Else
            Checker = ("Not matched")
        End If
    End If
End Function

我希望如果在单元格“A1”中说GB,那么它会检查“A2”中的邮政编码,并与英国的regEx模式进行比较。如上所述,它将包含多个国家。
非常感谢大家

vjhs03f7

vjhs03f71#

我会修改这个函数,让它接受两个参数,第一个是国家代码,第二个是邮政编码。
我更喜欢删除Range类型,并明确地说它是某种String类型的数据。所以在这种情况下,我们可以假设国家代码的第二个参数可能是一个范围。但是,然后你必须循环每个单元格,用正则表达式测试它们。如果一个邮政编码无效,那么停止循环并返回“无效邮政编码”或者类似的东西。如果你需要的话,我会让你做的。但是我认为你只是想验证一个特定国家代码的单个邮政编码。
在这里,我只是做了4个国家,作为一个例子。你必须检查下维基百科,像我一样,找到每个国家的规则。

Option Explicit

Function CheckPostalCode(strCountryCode As String, strPostalCode As String) As String
    ' Reference : Microsoft VBScript Regular Expressions 5.5
    Dim PostalCodeRegExp As New RegExp
    
    ' Prepare the postal code regular expression object.
    With PostalCodeRegExp
        .Global = False     ' We don't want multiple matches.
        .MultiLine = False  ' We don't want ^ and $ to match begin and end of lines.
        .IgnoreCase = False ' We want to be case sensitive.
    End With

    ' We'll get rid of spaces around and convert to uppercase for the tests below.
    Select Case Trim(UCase(strCountryCode))
        Case "CH", "CHE"
            PostalCodeRegExp.Pattern = "^[1-9][0-9]{3}$" ' DDDD but from 1000 to 9999 only
        Case "FR", "FRA"
            PostalCodeRegExp.Pattern = "^(?:0[1-9]|[1-8]\d|9[0-8])\d{3}$"
        Case "GB", "GBR", "UK"
            PostalCodeRegExp.Pattern = "^(([A-Z]{1,2}[0-9][A-Z0-9]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?[0-9][A-Z]{2}|BFPO ?[0-9]{1,4}|(KY[0-9]|MSR|VG|AI)[ -]?[0-9]{4}|[A-Z]{2} ?[0-9]{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$"
            ' In case you want to make it case insensitive just for
            ' Great Britain then uncomment the line below.
'            PostalCodeRegExp.IgnoreCase = True
        Case "US", "USA"
            PostalCodeRegExp.Pattern = "^\d{5}(?:[-\s]\d{4})?$" ' DDDDD or DDDDD-DDDD
        Case Else
            CheckPostalCode = "Unknown country code"
            Exit Function
    End Select
    
    If PostalCodeRegExp.Test(strPostalCode) Then
        CheckPostalCode = "Valid postal code"
    Else
        CheckPostalCode = "Invalid postal code"
    End If
End Function

相关问题