MAC地址重新格式化中的额外分隔符

时间:2014-05-20 15:50:23

标签: c# regex

我在这里看了几个关于格式化和验证MAC地址的问题,这是我开发正则表达式的地方。我遇到的问题是,当我去更新字段时,在新格式化的MAC中有额外的分隔符,或者如果不存在分隔符,则MAC无法验证。我是新手使用正则表达式,所以有人可以澄清为什么会这样吗?

if (checkMac(NewMacAddress.Text) == true)
{
    string formattedMAC = NewMacAddress.Text;
    formattedMAC.Replace(" ", "").Replace(":", "").Replace("-", ""); //attempt to remove the delimiters before formatting
    var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";
    var replace = "$1:$2:$3:$4:$5:$6";
    var newformat = Regex.Replace(formattedMAC, regex, replace);
    NewMacAddress.Text = newformat.ToString();
}

这是checkmac函数

protected bool checkMac(string macaddress)
    {
        macaddress.Replace(" ", "").Replace(":", "").Replace("-", "");
        Regex r = new Regex("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$");

        if (r.Match(macaddress).Success)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

这是我正在讨论的额外分隔符的示例输出。 00 :: 5:0:56 :: B:F:00:1408米 我能够从文本框中获取原始MAC。我从屏幕抓取中得到的MAC地址也会出现这种情况。

2 个答案:

答案 0 :(得分:1)

您的代码无法正常工作的原因是:

  1. String.Replace不会修改您传入的字符串,而是返回一个新字符串(字符串为immutable)。您必须将String.Replace的结果分配给变量。
  2. 您的checkMac函数仅允许带有分隔符的mac地址。您只需删除此限制即可解决问题。
  3. 然后,工作代码变成了以下内容:

    string newMacAddress = "00::5:0::56::b:f:00:7f";
    if (checkMac(newMacAddress) == true)
    {
        string formattedMAC = newMacAddress;
        formattedMAC = formattedMAC.Replace(" ", "").Replace(":", "").Replace("-", ""); //attempt to remove the delimiters before formatting
        var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";
        var replace = "$1:$2:$3:$4:$5:$6";
        var newformat = Regex.Replace(formattedMAC, regex, replace);
        newMacAddress = newformat.ToString();
    }
    
    protected static bool checkMac(string macaddress)
    {
        macaddress = macaddress.Replace(" ", "").Replace(":", "").Replace("-", "");
        Regex r = new Regex("^([0-9A-Fa-f]{12})$");
    
        if (r.Match(macaddress).Success)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    

答案 1 :(得分:0)

你很亲密。我首先要使用Ruby来回答,因为这是我目前最熟悉的东西,它应该足以让你理解如何让它在C#中运行。也许我可以稍后将其转换为C#。

使用这些元素:

  • \A - 整个字符串的开头
  • [0-9a-fA-F] - 任何十六进制数字
  • {2} - 两次
  • [:-]? - “:”或“ - ”或“”(无分隔符)
  • \Z - 整个字符串的结尾,在结束换行符之前(如果存在)
  • () - 括号内的匹配,以引用正则表达式的部分内容,例如: match[1]

这个正则表达式将满足您的需求:

mac_address_regex = /\A([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})[:-]?([0-9a-fA-F]{2})\Z/

您可以使用此正则表达式验证和清理输入:

match = mac_address_regex.match(new_mac_address.text)
if match.present?
  sanitized_mac_addr = (1..6).map { |i| match[i] }.join(":") # join match[i] for i = (1,2,3,4,5,6)
  sanitized_mac_addr.upcase!                                 # uppercase
else
  sanitized_mac_addr = nil
end