字符串格式固定绑定字符,里面的变量字符

时间:2014-02-13 16:26:33

标签: c# string-formatting

我想将数字格式化为字符串,格式如下:

String.Format(phone, "(00) ##000\-0000");

所以:

112349999   -> (11) 234-9999
1123459999  -> (11) 2345-9999
11234569999 -> (11) 23456-9999

(将只读取我国允许的这些手机格式)

  1. 将2个第一位数字固定在“(XX)”中。
  2. 最后4位数字修正为“-XXXX”
  3. 内部数字(其他数字),从“ - ”开始(每个字符串从右边第6个位置插入,将另一个字符串插入(XX))。
  4. 我无法使用String.Format()的简单格式实现此行为。

    有办法吗?

2 个答案:

答案 0 :(得分:2)

string phone = "112223333";
var m = Regex.Match(phone, @"(\d{2})(\d+)(\d{4})");
var formatted = String.Format("({0}) {1}-{2}", m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);

答案 1 :(得分:0)

由于中间部分的数字位数可变,因此您无法在此处使用String.Format。试试这个:

String.Format("({0}) {1}-{2}",
    phone.Substring(0, 2),
    phone.Substring(2, phone.Length - 6),
    phone.Substring(phone.Length - 4))
);