我有一个简单的问题,我有一部这样的电话:+1 (123) 123-1234,我想使用正则表达式从该字符串中取出数字。
simple_question
问问题
844 次
4 回答
13
这将去掉一个非数字字符:
string input = "+1 (123) 123-1234";
string digits = Regex.Replace(input,@"\D",string.Empty);
于 2009-04-21T22:10:03.117 回答
6
使用 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());
最终结果是相同的,但我认为在这种情况下 LINQ 比 RegEx 提供了一些优势。首先,可读性。RegEx 要求您知道“D”表示非数字(与 Char.IsDigit() 相比)- 这里的评论中已经存在混淆。另外,我做了一个非常简单的基准测试,每个方法执行 100,000 次。
LINQ:127 毫秒
正则表达式:485 毫秒
因此,乍一看,似乎 LINQ 在这种情况下执行了正则表达式。而且,我认为它更具可读性。
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();
于 2009-04-21T22:54:02.073 回答
2
string digits = Regex.Replace(input, @"[^\d]", String.Empty);
于 2009-04-21T22:12:35.373 回答
-2
为什么不直接更换?
string phoneNumber = "+1 (123) 123-1234";
phoneNumber = phoneNumber.Replace("+", "");
phoneNumber = phoneNumber.Replace("(", "");
phoneNumber = phoneNumber.Replace(")", "");
phoneNumber = phoneNumber.Replace("-", "");
phoneNumber = phoneNumber.Replace(" ", "");
于 2009-04-21T22:11:33.800 回答