• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 411
  • Last Modified:

Regex Screpts to Edit phone Number

I need to create a script that will force the phone number to be in this format"  999 999-9999.  No parentheses or hyphen between area code and next 3 digits.  To force only numerics, no other formats but that one.  Can anyone help me with this?
0
garyinmiami2003
Asked:
garyinmiami2003
  • 6
  • 4
  • 4
2 Solutions
 
Fernando SotoCommented:
Hi garyinmiami2003;

Here is a solution using Regex.

Imports System.Text.RegularExpressions

        ' Sample data
        Dim phoneNumber As String = "  (555)-555-1234 "

        ' Regex patterns
        Dim pattern As String = "^\s*\(?\s*(\d{3})\s*\)?-?\s*(\d{3})-?\s*(\d{4})\s*$"
        Dim replacement As String = "$1 $2-$3"

        Dim phoneFormatted As String = Regex.Replace(phoneNumber, pattern, replacement)

        MessageBox.Show(phoneFormatted)


Fernando
0
 
garyinmiami2003Author Commented:
Fernando:

The script does not do what I need:

Unfortunately, I need to force the phone number to look exactly like this:

999 999-9999   where each '9' is a digit 0-9, specifically a blank between AC and next 3 digits, hyphen between middle 3 digits and last 4  
0
 
Fernando SotoCommented:
What does the input look like or possibilities of it looking like.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
garyinmiami2003Author Commented:
I am forcing the user to enter exactly like the script when they leave textbox.

So anything entered other than 999 999-9999   will display messagebox and refocus back to textbox to fix.  Does that help A correct entry would be:

305 111-2222

Incorrect:   (305)111-2222, 305-111-2222, 305 111 2222, 1-305-111-1111)  All incorrect

 
0
 
neilpriceCommented:
Hi,

This code example works for all of your incorrect examples;

Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        Dim r As Regex = New Regex(".*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d)")
        Dim phonenumber As String = "(949)944-9933"
        Dim s As String = ""
        s += r.Match(phonenumber).Groups(1).ToString()
        s += r.Match(phonenumber).Groups(2).ToString()
        s += r.Match(phonenumber).Groups(3).ToString() + " "
        s += r.Match(phonenumber).Groups(4).ToString()
        s += r.Match(phonenumber).Groups(5).ToString()
        s += r.Match(phonenumber).Groups(6).ToString() + "-"
        s += r.Match(phonenumber).Groups(7).ToString()
        s += r.Match(phonenumber).Groups(8).ToString()
        s += r.Match(phonenumber).Groups(9).ToString()
        s += r.Match(phonenumber).Groups(10).ToString()
        Console.WriteLine(s)
        Console.ReadLine()
    End Sub

End Module
0
 
garyinmiami2003Author Commented:
That takes care of a part of the problem that I am trying to achieve:

What I was using:



Private Function NumberOK(ByVal testString As String) As Boolean

                 Dim r As New Regex("(\(?)(\d{3})(\)?)([\s\-]?)(\d{3})-(\d{4})")
              Return r.IsMatch(testString)

end function



On lostFocus event for Phone textbox
 If txtCMPhone.Text <> "" Then
            If NumberOK(txtCMPhone.Text) Then
                'show your OK message
                '  MessageBox.Show("Ok Phone")
            Else
                'show your error message
                MessageBox.Show("Phone Number Invalid format try 'xxx-xxx-xxxx' ")
                Me.txtCMPhone.Focus()
            End If

        End If

With your module, it will replace most of the common mistakes.  The end result is I do not want them to be able to enter any other formats.  There options should be to enter nothing or to enter phone # in exactly the format 999 999-9999

It almost will work if I use the script I already had + your module but could we refine it a little?  Then I will be happy to close this question and be hubly grateful for your help?
   
0
 
Fernando SotoCommented:
Hi garyinmiami2003;

Tiis code will take the phone number formatted in this format

    (305)111-2222          and tuen it into this format 305 111-2222
    305-111-2222           and tuen it into this format 305 111-2222
    305 111 2222            and tuen it into this format 305 111-2222
    1-305-111-1111        and tuen it into this format 305 111-1111

        Dim pattern As String = "^\s*\(?\s*(\d{3})\s*\)?-?\s*(\d{3})-?\s*(\d{4})\s*$"
        Dim replacement As String = "$1 $2-$3"

        If Regex.IsMatch(TextBox1.Text, pattern) Then
            TextBox1.Text = Regex.Replace(TextBox1.Text, pattern, replacement)
        Else
            MessageBox.Show("The phone number is in the wrong format.")
            'Return user to the Textbox to re-enter the phone number
        End If

But if you want to just validate the phone and have the user re-enter the number then this will work

        Dim pattern As String = "^\d{3}\s\d{3}-\d{4}$"

        If Regex.IsMatch(TextBox1.Text, pattern) Then
            MessageBox.Show("Good Format")
        Else
            MessageBox.Show("Invalid Format")
        End If


Fernando
0
 
neilpriceCommented:
Hi,

If you want to limit the input from the user perhaps a masked text box may be a better option than using Regexs?

If you're using .NET 2.0 you can use the included control "MaskedTextBox" with a mask of '999 000-0000'

If you're not you can find a masked text box here;
http://www.codeproject.com/cs/miscctrl/maskedcsedit.asp

Hope this helps,
Neil
0
 
Fernando SotoCommented:
Hi neilprice;

The pattern you give in your solution, ".*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d).*(\d)", will also pull all the digits out of this string, aaa(9b4c9)d9e4g4'-9;93m3 and format it to 949 944-9933. But this is not what the author wants.

Fernando
0
 
neilpriceCommented:
Hi FernandoSoto,
Yes I realise my solution will pull 9 digits out of anything like that.  The idea was to reformat the illegal examples he gave correctly.  Having re-read through his original question and subsequent responses I think replacing the textbox with some kind of maskedtextbox will provide the best return.  (as stated in my previous response)
Thanks,
Neil
0
 
Fernando SotoCommented:
Hi garyinmiami2003;

Then use this Regex pattern with your code

    Private Function NumberOK(ByVal testString As String) As Boolean

        Dim r As New Regex("^\d{3}\s\d{3}-\d{4}$")
        Return r.IsMatch(testString)

    end function

Fernando
0
 
garyinmiami2003Author Commented:
Fernando and Neil:

My thanks to you both.  Fernando, the last Regex script is just exactly what I needed.  My thanks to you both.  Both of you provided code that I can use.  In my book you both deserve 500 points.  If no one has an objection I would like to accept Fernando's answer award 350 to Fernando and 150 to Neil.  I will give 5 minutes for any comment or dissent and then close.

gary
   
0
 
neilpriceCommented:
Gary,

No objections here, glad I could have some useful input!

Neil
0
 
Fernando SotoCommented:
No problem, Only glad I as able to help. :=)
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now