Solved

Regex Screpts to Edit phone Number

Posted on 2006-06-12
14
404 Views
Last Modified: 2008-01-09
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
Comment
Question by:garyinmiami2003
  • 6
  • 4
  • 4
14 Comments
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 16885634
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
 

Author Comment

by:garyinmiami2003
ID: 16886029
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
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 16886138
What does the input look like or possibilities of it looking like.
0
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.

 

Author Comment

by:garyinmiami2003
ID: 16886191
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
 
LVL 6

Assisted Solution

by:neilprice
neilprice earned 150 total points
ID: 16886314
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
 

Author Comment

by:garyinmiami2003
ID: 16886608
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
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 16886610
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
 
LVL 6

Expert Comment

by:neilprice
ID: 16886667
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
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 16886685
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
 
LVL 6

Expert Comment

by:neilprice
ID: 16886717
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
 
LVL 63

Accepted Solution

by:
Fernando Soto earned 350 total points
ID: 16886774
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
 

Author Comment

by:garyinmiami2003
ID: 16886809
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
 
LVL 6

Expert Comment

by:neilprice
ID: 16886828
Gary,

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

Neil
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 16886847
No problem, Only glad I as able to help. :=)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question