1

必须有一种更简单的方法来做到这一点。

我正在尝试为一个名为“导入电话号码”的电话号码类编写一个函数。它应该在某个地方使用任何包含 10 位数字的字符串(并允许扩展),并将它们导入到它自己的属性中:AreaCode、Prefix、Suffix 和 Extension (aaa-ppp-ssss-xxxx ...)。

我用正则表达式检查输入以确保它有效,现在我想将这些部分标记为它们各自的属性。我所拥有的看起来像这样(不完整):

Public Sub ImportPhoneNumber(ByVal anyNumber As String)
    'phone number is 10-digits long, e.g.: 012-345-6789
    Dim reg_exp_10 As New Regex("^((\D*)\d(\D*)){9}((\D*)\d){1}(((x|ext){1}(\d)+)?|\D*)$", RegexOptions.IgnoreCase)

    If reg_exp_10.IsMatch(anyNumber) Then
        Dim areacode As String = HRITS.Constants.DEFAULT_STRING_VALUE
        Dim prefix As String = HRITS.Constants.DEFAULT_STRING_VALUE
        Dim suffix As String = HRITS.Constants.DEFAULT_STRING_VALUE
        Dim loadExtension As Boolean = False
        Dim count As Integer = 0
        'for each char in anynumber, is it a number? concatenate it onto holder number
        For Each i As Char In anyNumber
            'first 3 hits, load areacode
            If count < 3 Then
                If Char.IsDigit(i) Then
                    areacode = String.Concat(areacode, i)
                    count = count + 1
                End If
            End If
            'second 3 hits, load prefix
            If count >= 3 AndAlso count < 6 Then
                If Char.IsDigit(i) Then
                    prefix = String.Concat(prefix, i)
                    count = count + 1
                End If
            End If
            'third 4 hits, load suffix
            If count >= 6 AndAlso count < 10 Then
                If Char.IsDigit(i) Then
                    suffix = String.Concat(suffix, i)
                    count = count + 1
                End If
            End If

            If count >= 10 Then
                If i.ToString = "x" Then
                    loadExtension = True
                ElseIf i.ToString = "e" Then

                End If
            End If

        Next
    Else
        Throw New Exception(ErrorMessages.PhoneNumber.INVALID_NUMBER)
    End If

End Sub

有任何想法吗?

4

1 回答 1

1

开始了:

/(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)/

分别在捕获组 1 到 4 中的区号、前缀、后缀、扩展名。

于 2010-01-25T23:12:01.797 回答