代码之家  ›  专栏  ›  技术社区  ›  ChiliYago

字符串。设置带分机的电话号码格式

  •  6
  • ChiliYago  · 技术社区  · 14 年前

    我正在尝试创建一个格式化我们电话号码的函数——希望不会在每个数字之间循环。

    当10位数字全部通过时就可以了。当超过10个数字被传入时 我想用string.format方法在右边附加扩展数字。例如:

    当14位数字通过时,结果应为:(444)555-2222 x8888 当12位数字通过时,结果应为:(444)555-2222 x88 等。 然而,我目前的尝试是: 传入12位返回字符串'()-949 x555444433'

    这是我到目前为止所拥有的。

    public static string _FormatPhone(object phonevalue)
    {
        Int64 phoneDigits;
    
        if (Int64.TryParse(phonevalue.ToString(), out phoneDigits))
        {
            string cleanPhoneDigits = phoneDigits.ToString();
            int digitCount = cleanPhoneDigits.Length;
    
            if (digitCount == 10)
                return String.Format("{0:(###) ###-####}", phoneDigits);
            else if (digitCount > 10)
                return String.Format("{0:(###) ###-#### x#########}", phoneDigits);
            else
                return cleanPhoneDigits;
        }
    
        return "Format Err#";
    }
    

    事先谢谢。

    6 回复  |  直到 8 年前
        1
  •  2
  •   Ax.    14 年前

    我想你得把电话号码串分成前10个数字和其余的数字。

    //[snip]
    else if (phoneDigits.ToString().Length > 10)
            {
                return String.Format("{0:(###) ###-#### x}{1}", phoneDigits.Substring(0,10), phoneDigits.Substring(10) );
            }
    //[snip]
    
        2
  •  1
  •   Steven Sudit    14 年前

    我建议把它当作一串数字,而不是数字。然后您将显式地使用子字符串分隔各个部分。

        3
  •  1
  •   Pete    8 年前

    我试着把它挤成一行,就想到了这个。

    var phoneNumber = "(999) 555-4455 ext123";
    phoneNumber = Regex.Replace(phoneNumber, "(.*?)([+]\\d{1,3})?(.*?)(\\d{3})(.*?)(\\d{3})(.*?)(\\d{4})([ ]+)?(x|ext)?(.*?)(\\d{2,5})?(.*?)$", "$2 $4 $6 $8 $10$12").Trim().Replace("ext","x");
    

    如果它以+开头,它将不受影响。然后它将查找数字块。3,3,4然后它会查找ext或x作为扩展名和另外2-5个数字。在这一点上,你可以格式化它无论你喜欢,我选择了空间。

    1234567890->'123 456 7890'

    (123)456.7890->'123 456 7890'

    +1(999)555-4455外接123->'+1 999 555 4455 x123'

        4
  •  0
  •   Ahmad Mageed    14 年前

    问题在于你 else if 当你有一个设定的数字 # 用于处理电话号码扩展的占位符。相反,我们可以动态地定义格式来考虑不同的长度。

    你为什么要进来 object ?你在用 ToString() 到处都是。为什么不通过 string 从一开始?如果传递的项不是字符串,则调用 ToString 在传递之前,或者保存 托斯特林() 在方法中生成一个变量,如下所示。

    以下是方法的更新版本:

    public static string _FormatPhone(object phonevalue)
    {
        string returnPhone = "Format Err#";
    
        Int64 phoneDigits;
        string phoneNumber = phonevalue.ToString();
    
        if (Int64.TryParse(phoneNumber, out phoneDigits))
        {
            if (phoneNumber.Length == 10)
            {
                return phoneDigits.ToString("(###) ###-####");
            }
            else if (phoneNumber.Length > 10)
            {
                // determine the length of placeholders needed for the format
                string format = "(###) ###-#### x"
                                    + new string('#', phoneNumber.Length - 10);
                return phoneDigits.ToString(format);
            }
            else
            {
                return phoneNumber;
            }
        }
    
        return returnPhone;
    }
    

    测试它:

    string[] inputs = { "456", "4445552222", "444555222288", "44455522226789" };
    foreach (string input in inputs)
    {
        Console.WriteLine("Format Result: " + _FormatPhone(input));
    }
    

    在这种情况下不需要正则表达式。如果您真的想使用扩展名,那么您的替换方法需要确定长度,以便在需要时附加扩展名,如下所示:

    string[] inputs = { "456", "4445552222", "444555222288", "44455522226789" };
    string pattern = @"(\d{3})(\d{3})(\d{4})(\d*)";
    foreach (string input in inputs)
    {
        string result = Regex.Replace(input, pattern, m =>
        {
            if (m.Value.Length >= 10)
            {
                return String.Format("({0}) {1}-{2}",
                    m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value)
                        + (m.Value.Length > 10 ? " x" + m.Groups[4].Value : "");
            }
            return m.Value;
        });
        Console.WriteLine("Regex result: " + result);
    }
    
        5
  •  0
  •   Ray    14 年前

    使用正则表达式:

    Regex usPhoneRegex = new Regex(@"(\d{3})(\d{3})(\d{4})(.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    string USPhoneFormatString = "$1-$2-$3 x$4";
    return usPhoneRegex.Replace("312588230012999", USPhoneFormatString));
    

    主电话号码之后的任何内容都将作为分机返回

    因为您在代码中使用的是Int64,所以我的regex假定电话号码中没有空格或标点符号。

    --编辑—— 艾哈迈德指出,我没有处理一个没有扩展名的数字的情况。所以这里有一个修订版,它使用matchEvaluator来完成这项工作。它比其他答案更好吗?我不知道-但这是一个不同的方法,所以我想我会把它扔出去。

    Regex usPhoneRegex = new Regex(@"(\d{3})(\d{3})(\d{4})(.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    return usPhoneRegex.Replace("3125882300", new MatchEvaluator(MyClass.formatPhone))
    
    public static string formatPhone(Match m) {
      int groupIndex = 0;
      string results = string.Empty;
      foreach (Group g in m.Groups) {
        groupIndex +=1;
        switch (groupIndex) {
          case 2 : 
            results = g.Value;
            break;
          case 3 : 
          case 4 : 
            results += "-" + g.Value;
            break;
          case 5 :
            if (g.Value.Length != 0) {
              results += " x " + g.Value;
            }
            break;
        }
      }
      return results;
    }
    

    这可能需要使用StringBuilder。

        6
  •  0
  •   Tim Cooper    13 年前

    尝试使用正则表达式:

    class Program
        {
            static void Main(string[] args)
            {
                var g = FormatUSPhone("444555222234");
    
            }
    
            public static string FormatUSPhone(string num)
            {
                string results = string.Empty;
    
                if(num.Length == 10)
                {
                    num = num.Replace("(", "").Replace(")", "").Replace("-", "");
                    const string formatPattern = @"(\d{3})(\d{3})(\d{4})";
    
                    results = Regex.Replace(num, formatPattern, "($1) $2-$3");
    
                }else if (num.Length == 12)
                {
                    num = num.Replace("(", "").Replace(")", "").Replace("-", "");
                    const string formatPattern = @"(\d{3})(\d{3})(\d{4})(\d{2})";
    
                    results = Regex.Replace(num, formatPattern, "($1) $2-$3 x$4");
                }
    
                return results;
            }
    

    我从我发现的一个例子中编辑了以上内容 here . 玩一下上面的代码,看看它是否对你有帮助。