我想将数字格式化为字符串,格式如下:
String.Format(phone, "(00) ##000\-0000");
所以:
112349999 -> (11) 234-9999
1123459999 -> (11) 2345-9999
11234569999 -> (11) 23456-9999
(将只读取我国允许的这些手机格式)
我无法使用String.Format()的简单格式实现此行为。
有办法吗?
答案 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))
);