格式化电话号码

时间:2014-05-08 15:07:39

标签: c# regex formatting phone-number

如何将电话号码格式化为(###)### - ####至##########?有最好的方法吗?我可以使用String.Substring来获取每个数字块,然后将它们连接起来。但是,还有其他复杂的方法吗?

4 个答案:

答案 0 :(得分:3)

简单的正则表达式取代怎么样?

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

这基本上只是一个数字的白名单。看到这个小提琴:http://dotnetfiddle.net/ssdWSd

输入:(123)456-7890

输出:1234567890

答案 1 :(得分:3)

我是用LINQ做的:

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

虽然正则表达式也有效,但这不需要任何特殊设置。

答案 2 :(得分:0)

一种简单的方法是:

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

用空字符串替换每个字符。

答案 3 :(得分:-1)

试试这个:

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»
相关问题