Solved

How to strip out phone number in string in c#?

Posted on 2015-02-15
9
94 Views
Last Modified: 2015-02-19
Per the following code I'm trying to strip out any semblance of a phone number out of a string - but all I get is the exact value I send...

The string contains this:  "Abbott Laboratories Diag Div       ((800) 323-9100)"
Another example of a string that may occur is:   (Phone 800-255-8522)
For the most part strings are being passed with just:  (Phone: )
so I still need that type stripped out.


The function I have is this:

 private static string NoPhoneNumber(string sValue)
        {
            string newvalue = "";
            if (sValue.IndexOf("(Phone: )") == -1)
            {
                newvalue = sValue;
            }
            else
            {
                newvalue = sValue.Contains("(Phone: )") ? sValue.Substring(0, sValue.IndexOf("(Phone: )")) : "";
            }


            return newvalue;

        }

Open in new window


How may I change the syntax above to allow for phone numbers be gone from the string?

Thank you in advance!
0
Comment
Question by:stephenlecomptejr
  • 4
  • 4
9 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi Stephen;

This code snippet will do what you want in stripping out the phone numbers.

using System.Text.RegularExpressions;

private static string NoPhoneNumber(string sValue)
{
     // This is a regular expression pattern to parse the string
    string pattern = @"(\(\(\d{3}\) \d{3}-\d{4}\))|(\(Phone \d{3}-\d{3}-\d{4}\))|(\(Phone: \))";
    
    return Regex.Replace(sValue, pattern, "");
}

Open in new window

0
 
LVL 1

Author Comment

by:stephenlecomptejr
Comment Utility
Hey Fernando,

I tried it and it got most of the phone numbers with the exception of these formats:

(408-716-4600)
((201) 825-9500 )
(312 523 2020)
(800 444-3940)
(800.776.4747 )
(800-953-1900)

I'm curious as to how would you rewrite the RegEx to keep what you're fixing and also be able to adjust these values?
0
 
LVL 1

Author Comment

by:stephenlecomptejr
Comment Utility
I tried it and it got most of the phone numbers stripped out of the string with the exception of these formats:
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi Stephen;

Replace the original pattern string with the one below. Regular expressions match only specific patterns.

string pattern = @"(\((\()?\d{3}(\))?[-\. ]\d{3}[-\. ]\d{4}\s{0,}\))|(\(Phone \d{3}-\d{3}-\d{4}\))|(\(Phone: \))";

Open in new window

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:stephenlecomptejr
Comment Utility
I found two more...

shouldn't the pattern above:  (\(Phone \d{3}-\d{3}-\d{4}\)) should have taken away (Phone 800-228-3952)?

(Phone 800-228-3952)
(Phone (800) 323-1245 x6159)

If there are any more found, I won't post anymore.
I just want to take care of these 2 more...

Thank you for all the replies.
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
Comment Utility
OK, try this pattern.

string pattern = @"(\((\()?\d{3}(\))?[-\. ]\d{3}[-\. ]\d{4}\s{0,}\))|(\(Phone (\()?\d{3}(\))?[-\s]\d{3}-\d{4}(\))?(\sx\d{4}\))?)|(\(Phone: \))";

Open in new window

0
 
LVL 22

Expert Comment

by:plusone3055
Comment Utility
I have two ways to do with it with Validation.

     //METHODS
        private bool isValid(string str)
        {
            const int VALID_NUMBER = 10;
            bool valid = true;

            // check the numbers legth it needs to be 8
            if (str.Length == VALID_NUMBER)
            {
                foreach (char ch in str)
                {
                    // if any charater in the number isn't a digit
                    if (!char.IsDigit(ch))
                    {
                        valid = false;
                    } // end if
                    
                } // end for each 

            }// end if 

            else // incorrect length 
               
            {
                valid = false;
            }
            return valid;
        }// end Bool 

        private void TelephoneFormat (ref string str)
        {
            //first insert teh left paranthesis at position 0 
            str = str.Insert(0, "(");

            //next insert the right paranthesis at position 4
            str = str.Insert(4, ")");

            // next insert the hyphen in position 8 
            str = str.Insert(8, "-");

        }
        private void formatButton_Click(object sender, EventArgs e)
        {
            // get a trimmed copy of the users input 
            string input = txtPhoneNumber.Text.Trim();

            // if the input is valid 
            // foramt it and display it 
            if (isValid(input))
            {
                TelephoneFormat(ref input);
                MessageBox.Show(input);

            }// end if 

            else
            {
                MessageBox.Show("Invalid input");
            }// end else
        }

Open in new window


heres another way if for example the number was 800-got-food
 private bool isValid(string str, List<string> sList)
        {
            const int VALID_NUMBER = 10;
            bool valid = true;
            
            int count = 0;

            if (str.Length == VALID_NUMBER)
            {
                
                foreach (char ch in str )
                {
                    if (char.IsLetterOrDigit(ch))
                    {
                       //create the list to loop through
                        sList.Insert(count,ch.ToString());
                        count++;
                    }
                                            
                    else if(!char.IsLetterOrDigit(ch))
                    {
                        valid = false;
                    }// end if 
                }// end or each 
            }// end if length

            else // incorrect length 
            {
                valid = false;
            }
            return valid;
        }

        private void translateNumber(List<string> yList)
        {
            string strBuilder = "";

            // loop thorugh my list and convert letters into numbers 
            for (int i = 0;  i< yList.Count; i++) 
            {


                if (yList[i].ToString() == "a" || yList[i].ToString() == "A"
                    || yList[i].ToString() == "b" || yList[i].ToString() == "B"
                    || yList[i].ToString() == "c" || yList[i].ToString() == "C")
                {
                    yList[i] = "2";
                }
                else if (yList[i].ToString() == "d" || yList[i].ToString() == "D"
                    || yList[i].ToString() == "e" || yList[i].ToString() == "E"
                    || yList[i].ToString() == "f" || yList[i].ToString() == "F")
                {
                    yList[i] = "3";
                }

                else if (yList[i].ToString() == "g" || yList[i].ToString() == "G"
                    || yList[i].ToString() == "h" || yList[i].ToString() == "H"
                    || yList[i].ToString() == "i" || yList[i].ToString() == "I")
                {
                    yList[i] = "4";
                }

                else if (yList[i].ToString() == "j" || yList[i].ToString() == "J"
                    || yList[i].ToString() == "k" || yList[i].ToString() == "K"
                    || yList[i].ToString() == "l" || yList[i].ToString() == "L")
                {
                    yList[i] = "5";
                }
                else if (yList[i].ToString() == "m" || yList[i].ToString() == "M"
                    || yList[i].ToString() == "n" || yList[i].ToString() == "N"
                    || yList[i].ToString() == "o" || yList[i].ToString() == "O")
                {
                    yList[i] = "6";
                }
                else if (yList[i].ToString() == "p" || yList[i].ToString() == "P"
                    || yList[i].ToString() == "q" || yList[i].ToString() == "Q"
                    || yList[i].ToString() == "r" || yList[i].ToString() == "R"
                    || yList[i].ToString() == "s" || yList[i].ToString() == "S")
                {
                    yList[i] = "7";
                }
                else if (yList[i].ToString() == "t" || yList[i].ToString() == "T"
                    || yList[i].ToString() == "u" || yList[i].ToString() == "U"
                    || yList[i].ToString() == "v" || yList[i].ToString() == "V")
                {
                    yList[i] = "8";
                }
                else if (yList[i].ToString() == "w" || yList[i].ToString() == "W"
                    || yList[i].ToString() == "x" || yList[i].ToString() == "X"
                    || yList[i].ToString() == "y" || yList[i].ToString() == "Y"
                    || yList[i].ToString() == "z" || yList[i].ToString() == "Z")
                {
                    yList[i] = "9";
                }

                              

                strBuilder += yList[i].ToString();
                
            }

            // now format it 

            //first insert the left paranthesis at position 0 
            strBuilder = strBuilder.Insert(0, "(");

            //next insert the right paranthesis at position 4
            strBuilder = strBuilder.Insert(4, ")");

            // next insert the hyphen in position 8 
            strBuilder = strBuilder.Insert(8, "-");

            // display it 
            MessageBox.Show(strBuilder);
        }


        private void btntranslate_Click(object sender, EventArgs e)
        {
            string input = txtphone.Text;
            List<string> xList = new List<string>();
            if (isValid(input,xList))
            {
                translateNumber(xList);
            }
            else
            {
                MessageBox.Show("Invalid Input");
            }
        }

Open in new window

0
 
LVL 1

Author Closing Comment

by:stephenlecomptejr
Comment Utility
Sorry about the delay.
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Not a problem, glad to help.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

762 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now