I have a phone number (000) 000-0开发者_开发知识库000, I would like to convert it back to 0000000000, is there a way to do so?
Do you really want an integer? A phone number has no meaning as an integer.
Try this if you are using a string:
string fixedString = Regex.Replace(yourString, @"[()\s-]", "");
If you don't know what kind of characters could be in the string then try this:
string fixedString = Regex.Replace(yourString, @"[^\d]", "");
Int64 somePhone;
Int64.TryParse(Regex.Replace(yourString, @"[()\s-)]", ""), out somePhone)
How about doing it the old-fashioned but eminently readable way:
string Strip(string arg)
{
StringBuilder sb = new StringBuilder();
foreach (char c in arg.ToCharArray())
{
if (char.IsDigit(c))
{
sb.Append(c);
}
}
return sb.ToString();
}
It's also very slightly faster then RegEx (0.449 sec vs 0.472 sec for 10000 interations).0
Or for the sake of brevity & readibility (to us less-seasoned programmers :-) )
public static string GimmeNumbers(this string arg)
{
return new string(arg.ToCharArray().Where(c => char.IsDigit(c)).ToArray());
}
usage:
string phoneNo = "(000) 000-0000".GimmeNumbers();
or alternatively,
public static int GimmeNumbers(this string arg)
{
return int.Parse(new string(arg.ToCharArray().Where(c => char.IsDigit(c)).ToArray()));
}
... actually, thinking about it it's not that readable :-)
精彩评论