-2

I am looking for a way to take phone numbers Input from an end user, given the various ways that can be formatted, and reformat it in a more standardized way. My end users work with only US phone numbers. Looking at the C# port of google's LibPhoneNumber, I assume it was made for exactly this task, but I can't figure out its usage.

My goals for output is to standardize on 999-999-9999 format.

So if the user inputs (516)666-1234, I want to output 516-666-1234.

If the users inputs 5166661234, I want to output 516-666-1234.

If possible, if the user inputs (516)666-1234x102, I'd like the output to be 516-666-1234x102

If the library can't handle extensions, I'll deal with that problem externally.

What calls do I have to make to produce the desired output?

Alternatively, can you provide a link that provides the answer to my question?

Aheho
  • 12,622
  • 13
  • 54
  • 83
  • 3
    All that has been posted is a program description. However, we need you to [ask a question](http://stackoverflow.com/help/how-to-ask). We can't be sure what you want from us. Please [edit] your post to include a valid question that we can answer. Reminder: make sure you know [what is on-topic here](http://stackoverflow.com/help/on-topic), asking us to write the program for you and suggestions are off-topic. – gunr2171 Jan 18 '16 at 23:41
  • Since crappy question format, crappy quick way to fix this. Format string in order to remove first and fifth char and on the fourth position, add a dash. Use substrings. Knock yourself out – Kevin Avignon Jan 18 '16 at 23:50

1 Answers1

3

You have to combine RegEx (to string out non-numeric fields) and string formatting. Note that string.Format of a number is tricky, so we format the 10-digit phone number and then append the extension.

public string getPhoneNumber(string phone) {
   string result = System.Text.RegularExpressions.Regex.Replace(phone, @"[^0-9]+", string.Empty);
   if (result.Length <= 10) {
       return Double.Parse(result).ToString("###-###-####");
   } else {
       return Double.Parse(result.Substring(0,10)).ToString("###-###-####") + 
       "x " + result.Substring(10, result.Length-10);
   }
}

To do this right, I'd want to check for "1" at the start of my digits and ditch it. I'd want to check for < 10 characters and make some assumptions about area code, etc.

But - this is a good start.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
bri
  • 2,932
  • 16
  • 17