Solved

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

Posted on 2015-02-15
9
95 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
ID: 40610878
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
ID: 40610957
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
ID: 40610963
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
ID: 40611018
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 1

Author Comment

by:stephenlecomptejr
ID: 40611415
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
ID: 40611574
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
ID: 40616447
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
ID: 40619653
Sorry about the delay.
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40619678
Not a problem, glad to help.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
WKHTMLTOPDF - --disable-smart-shrinking not working 10 32
Host asp.net pages 5 25
Angular JS Route 3 45
C#.NET and microsoft certification. 3 25
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

914 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

12 Experts available now in Live!

Get 1:1 Help Now