【发布时间】:2014-05-08 15:07:38
【问题描述】:
如何将电话号码从 (###)###-#### 格式化为 ##########?有没有最好的方法来做到这一点?我可以使用String.Substring 来获取每个数字块,然后将它们连接起来。但是,还有其他复杂的方法吗?
【问题讨论】:
标签: c# regex formatting phone-number
如何将电话号码从 (###)###-#### 格式化为 ##########?有没有最好的方法来做到这一点?我可以使用String.Substring 来获取每个数字块,然后将它们连接起来。但是,还有其他复杂的方法吗?
【问题讨论】:
标签: c# regex formatting phone-number
简单的正则表达式替换怎么样?
string formatted = Regex.Replace(phoneNumberString, "[^0-9]", "");
这实际上只是一个数字白名单。看到这个小提琴:http://dotnetfiddle.net/ssdWSd
输入:(123) 456-7890
输出:1234567890
【讨论】:
+ 是不必要的,因为该函数将查找所有满足指定正则表达式的子字符串并替换它。
我会使用 LINQ:
var result = new String(phoneString.Where(x => Char.IsDigit(x)).ToArray());
虽然正则表达式也有效,但这不需要任何特殊设置。
【讨论】:
一个简单的方法是:
myString = myString.Replace("(", "");
myString = myString.Replace(")", "");
myString = myString.Replace("-", "");
用空字符串替换每个字符。
【讨论】:
试试这个:
resultString = Regex.Replace(subjectString, @"^\((\d+)\)(\d+)-(\d+)$", "$1$2$3");
正则表达式解释
^\((\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»
【讨论】: