Chr*_*tal 13
这将删除非数字字符:
string input = "+1 (123) 123-1234";
string digits = Regex.Replace(input,@"\D",string.Empty);
Run Code Online (Sandbox Code Playgroud)
使用RegEx是一种解决方案. 另一种方法是使用LINQ(假设您使用的是.Net 3.5)
string myPhone = "+1 (123) 123-1234";
string StrippedPhone = new string((from c in myPhone
where Char.IsDigit(c)
select c).ToArray());
Run Code Online (Sandbox Code Playgroud)
最终结果是一样的,但我认为LINQ在这种情况下比RegEx提供了一些优势.首先,可读性.RegEx要求您知道"D"表示非数字(与Char.IsDigit()相比) - 此处的评论中已经存在混淆.此外,我做了一个非常简单的基准测试,每个方法执行100,000次.
LINQ:127ms
RegEx:485ms
因此,快速浏览一下,看起来LINQ out在这种情况下执行正则表达式.并且,我认为它更具可读性.
int i;
int TIMES = 100000;
Stopwatch sw = new Stopwatch();
string myPhone = "+1 (123) 123-1234";
// Using LINQ
sw.Start();
for (i = 0; i < TIMES; i++)
{
string StrippedPhone = new string((from c in myPhone
where Char.IsDigit(c)
select c).ToArray());
}
sw.Stop();
Console.WriteLine("Linq took {0}ms", sw.ElapsedMilliseconds);
// Reset
sw.Reset();
// Using RegEx
sw.Start();
for (i = 0; i < TIMES; i++)
{
string digits = Regex.Replace(myPhone, @"\D", string.Empty);
}
sw.Stop();
Console.WriteLine("RegEx took {0}ms", sw.ElapsedMilliseconds);
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)