Solved

Regex Screpts to Edit phone Number

Posted on 2006-06-12
14
403 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 62

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 62

Expert Comment

by:Fernando Soto
ID: 16886138
What does the input look like or possibilities of it looking like.
0
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 

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 62

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 62

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 62

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 62

Expert Comment

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

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

770 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