Hey Everyone,
I have a simple problem I have a phone like this: +1 (123) 123-1234 and I want to just take the numbers out of that string using regex. Any help will be greatly appreciated.
Thanks
Hey Everyone,
I have a simple problem I have a phone like this: +1 (123) 123-1234 and I want to just take the numbers out of that string using regex. Any help will be greatly appreciated.
Thanks
This will strip out an non-numeric characters:
string input = "+1 (123) 123-1234";
string digits = Regex.Replace(input,@"\D",string.Empty);
Why not just do a replace?
string phoneNumber = "+1 (123) 123-1234";
phoneNumber = phoneNumber.Replace("+", "");
phoneNumber = phoneNumber.Replace("(", "");
phoneNumber = phoneNumber.Replace(")", "");
phoneNumber = phoneNumber.Replace("-", "");
phoneNumber = phoneNumber.Replace(" ", "");
string digits = Regex.Replace(input, @"[^\d]", String.Empty);
Using RegEx is one solution. Another way would be to use LINQ (provided you are using .Net 3.5)
string myPhone = "+1 (123) 123-1234";
string StrippedPhone = new string((from c in myPhone
where Char.IsDigit(c)
select c).ToArray());
The end result is the same, but I think LINQ offers some advantages over RegEx in this case. First, readability. The RegEx requires you to know that "D" means Non digit (compared to Char.IsDigit())- there is confusion about that already in the comments here. Also, I did a very simple benchmark, performing each method 100,000 times.
LINQ: 127ms
RegEx: 485ms
So, at a quick glance, it seems like LINQ out performs Regex in this situation. And, I'd argue it is more readable.
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();