c# - 在 C# 中使用 string.Format 格式化 MAC 地址

标签 c# string

我有一个格式为 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

最佳答案

重新格式化字符串以将其显示为 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));

关于c# - 在 C# 中使用 string.Format 格式化 MAC 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13584519/

相关文章:

c - 查找替换子串C

python - 格式化字典中键的输出

Java正则表达式从字符串中获取数字

c# - Sitecore Workflow 命令抛出 "Could not find command definition"错误

c# - 性能:Vector2 与 x/y

c# - 如何使用c#在DataGrid(WPF)中显示列表列表

C#加载文件按钮标签

c# - 将 Task.Run() 用于 Linq - 优化或瓶颈

PHP 一次从字符串中删除多个内容

Python:将类变量字符串转换为类类字符串