-5

How can I format a phone number from (###)###-#### to ##########? Is there best way to do that? I can use String.Substring to get each block of numbers and then concatenate them. But, Is there any other sophisticated way of doing it?

C_sharp
  • 408
  • 5
  • 26

4 Answers4

3

How about a simple Regex replace?

string formatted = Regex.Replace(phoneNumberString, "[^0-9]", "");

This is essentially just a white list for numbers only. See this fiddle: http://dotnetfiddle.net/ssdWSd

Input: (123) 456-7890

Output: 1234567890

tnw
  • 13,521
  • 15
  • 70
  • 111
3

I'd do it using LINQ:

var result = new String(phoneString.Where(x => Char.IsDigit(x)).ToArray());

While regex also works, this doesn't require any special set up.

Nathan A
  • 11,059
  • 4
  • 47
  • 63
0

A simple way would be:

myString = myString.Replace("(", "");
myString = myString.Replace(")", "");
myString = myString.Replace("-", "");

Replace each character with an empty string.

dckuehn
  • 2,427
  • 3
  • 27
  • 37
-1

Try this:

resultString = Regex.Replace(subjectString, @"^\((\d+)\)(\d+)-(\d+)$", "$1$2$3");

REGEX EXPLANATION

^\((\d+)\)(\d+)-(\d+)$

Assert position at the beginning of the string «^»
Match the character “(” literally «\(»
Match the regex below and capture its match into backreference number 1 «(\d+)»
   Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “)” literally «\)»
Match the regex below and capture its match into backreference number 2 «(\d+)»
   Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “-” literally «-»
Match the regex below and capture its match into backreference number 3 «(\d+)»
   Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of the string, or before the line break at the end of the string, if any (line feed) «$»

$1$2$3

Insert the text that was last matched by capturing group number 1 «$1»
Insert the text that was last matched by capturing group number 2 «$2»
Insert the text that was last matched by capturing group number 3 «$3»
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268