Parsing and formatting phone numbers in Visual Basic .NET

Let’s say you have a textbox that takes in phone numbers that could be in one of the following formats:
(123) 456-7890

123-456-7890

1234567890

You want to be able to read these different inputs as being the same number because they are the same number. You want your program to be format agnostic. Here’s a method for getting rid of the unimportant characters:

    Private Function JustNumbers(input As String) As String
        input = input.Trim()
        Dim result As String = String.Empty

        For i As Integer = 0 To input.Length - 1
            If Decimal.TryParse(input(i), NumberStyles.None) Then
                result &= input(i)
            End If
        Next

        Return result
    End Function

That’s great and all, but what if you want to reformat the digits that this function spits out as 1234567890? Use this:

Dim phoneNumber As String = String.Format("{0:(###) ###-####}", Long.Parse(digits))

This code unfortunately does not consider non-American ways of formatting phone numbers.

Leave a comment