Formatting string as phone number

  • Thread starter Thread starter greatbarrier86
  • Start date Start date
G

greatbarrier86

Hi,

I'm pulling a row out of my db that contains a phone number and i want to
manually format it. Unfortunately, the column type is varchar so
string.format doesn't seem to work so i am manually parsing. The problem is
that i need to remove any non-numeric characters. Is there any good way of
doing this? Here is my current method.

tempPhoneNumber = phoneNumber.Replace("-", "");
tempPhoneNumber = tempPhoneNumber.Replace("(", "");
tempPhoneNumber = tempPhoneNumber.Replace(")", "");
tempPhoneNumber = tempPhoneNumber.Replace(" ", "");

areaCode = tempPhoneNumber.Substring(0, 3);
firstThreeDigits = tempPhoneNumber.Substring(3, 3);
lastFourDigits = tempPhoneNumber.Substring(6, 4);
phoneNumber = "(" + areaCode + ")" + " " + firstThreeDigits + "-" +
lastFourDigits;

That works fine, but it only removes spaces, parens, and dashes. Is there a
good way for it to just remove ALL non-numeric values?

Thanks so much!
Jason
 
Thanks mark. What does the D represent?

Mark Rae said:
using System.Text.RegularExpressions;

string strRaw = "T0h1i2s3 4i5s6 7a8l9p0h1a2n3u4m5e6r7i8c";
string strNumericOnly = Regex.Replace(strRaw, @"\D", String.Empty);
 
Back
Top