我有一个格式为0018103AB839
的mac地址,我希望将其显示为:00:18:10:3A:B8:39
我正在尝试使用string.Format
执行此操作,但我无法找到确切的语法。
现在我正在尝试这样的事情:
string macaddress = 0018103AB839;
string newformat = string.Format("{0:00:00:00:00:00:00}", macaddress);
这甚至可能吗?或者我应该使用string.Insert
?
答案 0 :(得分:8)
重新格式化字符串以将其显示为MAC地址:
var macadres = "0018103AB839";
var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";
var replace = "$1:$2:$3:$4:$5:$6";
var newformat = Regex.Replace(macadres, regex, replace);
// newformat = "00:18:10:3A:B8:39"
如果要验证输入字符串,请使用此正则表达式(感谢J0HN):
var regex = String.Concat(Enumerable.Repeat("([a-fA-F0-9]{2})", 6));
答案 1 :(得分:5)
string input = "0018103AB839";
var output = string.Join(":", Enumerable.Range(0, 6)
.Select(i => input.Substring(i * 2, 2)));
答案 2 :(得分:1)
var strings = macadres
.Select((value, index) => new { Pair = index / 2, value })
.GroupBy(g => g.Pair )
.Select(g => g.Aggregate("", (accumulated, elem) => accumulated+elem.value));
string formatted = String.Join(":", strings);
答案 3 :(得分:1)
假设我们将Mac地址存储在long中。这是如何在格式化的字符串中使用它:
ulong lMacAddr = 0x0018103AB839L;
string strMacAddr = String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}",
(lMacAddr >> (8 * 5)) & 0xff,
(lMacAddr >> (8 * 4)) & 0xff,
(lMacAddr >> (8 * 3)) & 0xff,
(lMacAddr >> (8 * 2)) & 0xff,
(lMacAddr >> (8 * 1)) & 0xff,
(lMacAddr >> (8 * 0)) & 0xff);