I'm looking for a routine that will format a string of numbers as a UK phone number. The routine should account for UK area codes that require different formatting (i.e. London compared to Edinburgh compared to Worcester) as well as mobile numbers.
My phone numbers are stored in the database as strings, containing only numeric characters.
So far I have come up with this, but the performance seems poor.
/// <summary>
/// Formats a string as a UK phone number
/// </summary>
/// <remarks>
/// 02012345678 becomes 020 1234 5678
/// 01311234567 becomes 0131 123 4567
/// 01905123456 becomes 01905 123456
/// 07816123456 becomes 07816 123456
/// </remarks>
public static string FormatPhoneNumber(string phoneNumber)
{
string formattedPhoneNumber = null;
if (!string.IsNullOrEmpty(phoneNumber))
{
System.Text.RegularExpressions.Regex area1 = new System.Text.RegularExpressions.Regex(@"^0[1-9]0");
System.Text.RegularExpressions.Regex area2 = new System.Text.RegularExpressions.Regex(@"^01[1-9]1");
string formatString;
if (area1.Match(phoneNumber).Success)
{
formatString = "0{0:00 0000 0000}";
}
else if (area2.Match(phoneNumber).Success)
{
formatString = "0{0:000 000 0000}";
}
else
{
formatString = "0{0:0000 000000}";
}
formattedPhoneNumber = string.Format(formatString, Int64.Parse(phoneNumber));
}
return formattedPhoneNumber;
}
Thoughts welcomed on how to improve this...
Edit
My initial thoughts are that I should store phone numbers as numeric fields in the database, then I can go without the Int64.Parse and know that they are truly numeric.
Edit 2
The phone numbers will all be UK geographic or UK mobile numbers, so special cases like 0800 do not need to be considered