I need a C# Regex pattern to find telephone numbers in a string and reformat them.
The telephone numbers could be in any format, eg 00 0000 0000 or (00) 0000 0000 or +00 0 0000 0000 or 0000 0000 or 00-0000-0000 or similar formats. So I am basically looking for at least 8 characters of 0-9, plus, minus, space or brackets, up to 20 characters max. This string will only contain phone number(s) and a bit of text so there will be no problem with any other numbers.
I want to replace the numbers found with a hyperlink to that telephone number like the example below with the non-numbers stripped out of the A tag.
<a href="tel:0000000000">00 0000 0000</a>
This is the code I came up with myself which almost works:
string regex = @"(\b[0-9+\(][\(\)0-9 +-]{6,20}[0-9]\b)";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
litTelephone.Text = r.Replace(faculty.Telephone, "<a href=\"tel:$1\">$1</a>");
It works with many numbers except it doesn’t pick up this example +00 0 0000 0000 if it is at the start of the string (it drops off the leading plus). It also doesn’t remove the non-numbers from the A tag.
I don’t know why I am so crap at regular expressions!
In your regex, keeping exclusively a match if it is following a ”greater than” (>) will allow you to exclude the number that you want to change:
(?<=>)[\+]?(\b[0-9+\(][\(\)0-9 +-]{6,20}[0-9]\b)Something similar to this would also handles extension:
(?<=>)([\+0-9]{1,3}([ \.\-])?)?([\(]{1}[0-9]{3}[\)])?([0-9A-Z \.\-]{1,32})((x|ext|extension)?[0-9]{1,4}?)Sorry to excessively edit my answer.