Ric*_*ett 5 c# regex formatting user-interface
我正在寻找一个例程,将一串数字格式化为英国电话号码.该例程应考虑需要不同格式的英国区域代码(即伦敦与爱丁堡相比,与伍斯特相比)以及移动号码.
我的电话号码作为字符串存储在数据库中,仅包含数字字符.
到目前为止,我已经想出了这个,但表现似乎很差.
/// <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;
}
Run Code Online (Sandbox Code Playgroud)
关于如何改进这一点的想法受到欢迎
我最初的想法是,我应该将电话号码存储为数据库中的数字字段,然后我可以不使用Int64.Parse并知道它们是真正的数字.
电话号码都是英国地理或英国手机号码,因此不需要考虑像0800这样的特殊情况
Aln*_*tak 12
英国电话号码的长度从7位到10位不等,不包括前导零."区域"代码可以在2到4个(但偶尔为5个)数字之间变化.
所有显示每个数字前缀的区号和总长度的表都可以从OFCOM的网站获得.注意:这些表很长.
而且,对于确切放置空间的位置没有标准.有些人可能会把它们放在不同的地方,这取决于它产生文本的"可读性".