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?
Asked
Active
Viewed 661 times
-5

C_sharp
- 408
- 5
- 26
4 Answers
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
-
The `+` is unnecessary, as the function will look for all substrings which satisfy the regex specified and replace it. – wei2912 May 08 '14 at 15:14
-
@wei2912 You're right, fixed. – tnw May 08 '14 at 15:15
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
-
2This won't work as it assumes strings are mutable, which they aren't. – Daniel Kelley May 08 '14 at 15:19
-
-
-
It's cool. It was wrong earlier, and whoever it was probably won't come back. I can't believe how often I forget strings aren't mutable in c#. Sometimes it takes me 15 minutes of debugging before it hits me. – dckuehn May 08 '14 at 15:55
-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