views:

65

answers:

1

There has got to be an easier way to do this.

I am trying to wirte a function for a Phone number class called "import phone number". It should take any string with 10 digits in it somewhere (and allow for an extension), and import them into it's own properties: AreaCode, Prefix, Suffix, and Extension (aaa-ppp-ssss-xxxx...).

I check the input with a regex to make sure it's valid, now i want to tokenize those pieces into their respective properties. What I have looks like this (incomplete):

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

any ideas?

+1  A: 

Here we go:

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

Area Code, Prefix, Suffix, Extension in capture groups 1 through 4 respectively.

Anon.
This only got me started in the right direction, but I figured out how to use the Dot net regex stuff. I was ignorant of the key words "capture group".
Watki02