2014-05-08 176 views
-5

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

回答

3

一个简单的正则表达式替换如何?

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

这实质上只是一个白色的数字列表。看到此小提琴:http://dotnetfiddle.net/ssdWSd

输入:(123)456-7890

输出:1234567890

+0

'+'是不必要的,因为函数将查找满足指定的正则表达式的所有子字符串并将其替换。 – wei2912

+0

@ wei2912你是对的,修好了。 – tnw

0

一个简单的方法是:

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

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

+2

这不会工作,因为它假定字符串是可变的,他们不是。 –

+0

我总是忘记这一点。我的编辑工作? – dckuehn

+0

现在它会工作。 -1不是我的。 –

-1

尝试这种情况:

​​

REGEX说明

^\((\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» 
+1

谨慎解释倒票? –

3

我会使用LINQ做到这一点:

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

虽然正则表达式也适用,这并不需要任何特殊设置。