Richard Everett Richard Everett - 1 year ago 110
C# Question

Format string as UK phone number

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}";
formatString = "0{0:0000 000000}";

formattedPhoneNumber = string.Format(formatString, Int64.Parse(phoneNumber));

return formattedPhoneNumber;

Thoughts welcomed on how to improve this...


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

Answer Source

UK telephone numbers vary in length from 7 digits to 10 digits, not including the leading zero. "area" codes can vary between 2 and usually 4 (but occasionally 5) digits.

All of the tables that show the area code and total length for each number prefix are available from OFCOM's website. NB: These tables are very long.

Also, there's no standard for exactly where spaces are put. Some people might put them in difference places depending on how "readable" it makes the resulting text.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download