2 Replies - 3193 Views - Last Post: 20 January 2015 - 02:53 AM

#1 girasquid   User is offline

  • Barbarbar
  • member icon

Reputation: 108
  • View blog
  • Posts: 1,825
  • Joined: 03-October 06

Formatting a ten-digit phone number

Posted 23 November 2007 - 01:05 PM

Description: Just pass your ten-digit phone number to the function, and store the output.This snippet takes a ten-digit phone number and formats it, in the form (xxx) xxx-xxxx.
    Private Function formatPhoneNumber(ByVal number As String) As String
        Dim pattern As String = "^(?([1-9]d{2}))?D*?([1-9]d{2})D*?(d{4})$"
        Dim re As Match = Regex.Match(number, pattern.ToString())
        Dim formatted As String = "(" & re.Groups(1).ToString() & ") " & re.Groups(2).ToString() & "-" & re.Groups(3).ToString()
        Return formatted
    End Function


Is This A Good Question/Topic? 0
  • +

Replies To: Formatting a ten-digit phone number

#2 Jayman   User is offline

  • Student of Life
  • member icon

Reputation: 423
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Formatting a ten-digit phone number

Posted 23 November 2007 - 04:01 PM

You might want to consider adding error catching to handle if a user passes in a value that is not a 10 digit number.
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw   User is offline

  • Bouncy!
  • member icon

Reputation: 6563
  • View blog
  • Posts: 26,615
  • Joined: 12-December 12

Re: Formatting a ten-digit phone number

Posted 20 January 2015 - 02:53 AM

This doesn't work for me. I'd prefer to do this this way:
    Private Function FormatPhoneNumber(ByVal number As String) As String
        If number.Length <> 10 Then
            Return String.Empty     'not 10 characters
        End If
        Dim value As ULong
        If Not ULong.TryParse(number, value) Then
            Return String.Empty     'not all digits
        End If

        Dim pattern As String = "(\d{3})(\d{3})(\d{4})"
        Dim replacement As String = "($1) $2-$3"
        Dim formatted As String = New Regex(pattern).Replace(number, replacement)
        Return formatted
    End Function

This post has been edited by andrewsw: 21 January 2015 - 04:10 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1