从vb.net中的字符串导入电话号码

时间:2010-01-25 22:59:55

标签: vb.net regex tokenize

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

我正在尝试为称为“导入电话号码”的电话号码类创建一个功能。它应该在任何地方使用任何带有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

任何想法?

1 个答案:

答案 0 :(得分:1)

我们走了:

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

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