不同的MAC地址正则表达式

时间:2013-05-30 06:34:56

标签: java regex

匹配MAC地址的正确正则表达式是什么?我搜索了一下,但大多数questions and answers都不完整。它们只为the standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits, separated by hyphens - or colons :.提供正则表达式。但是,这不是现实世界的情况。许多路由器,交换机和其他网络设备供应商提供的格式如下:

3D:F2:C9:A6:B3:4F //<-- standard 
3D-F2-C9-A6-B3:4F //<-- standard
3DF:2C9:A6B:34F   
3DF-2C9-A6B-34F
3D.F2.C9.A6.B3.4F
3df2c9a6b34f // <-- normalized

到目前为止,我所拥有的是:

public class MacAddressFormat implements StringFormat {
  @Override
  public String format(String mac) throws MacFormatException {
    validate(mac);
    return normalize(mac);
  }

  private String normalize(String mac) {

    return mac.replaceAll("(\\.|\\,|\\:|\\-)", "");
  }

  private void validate(String mac) {


    if (mac == null) {
      throw new MacFormatException("Empty MAC Address: !");
    }
    // How to combine these two regex together ? 
    //this one 
    Pattern pattern = Pattern.compile("^([0-9A-Fa-f]{2}[\\.:-]){5}([0-9A-Fa-f]{2})$");
    Matcher matcher = pattern.matcher(mac);
    // and this one ? 
    Pattern normalizedPattern = Pattern.compile("^[0-9a-fA-F]{12}$");
    Matcher normalizedMatcher = normalizedPattern.matcher(mac);

    if (!matcher.matches() && !normalizedMatcher.matches()) {
      throw new MacFormatException("Invalid MAC address format: " + mac);
    }

  }
}

你如何在代码中结合两个正则表达式?

7 个答案:

答案 0 :(得分:5)

为什么这么多代码? 以下是如何“规范化”您的mac地址:

mac.replaceAll("[^a-fA-F0-9]", "");

这是验证它的方法:

public boolean validate(String mac) {
   Pattern p = Pattern.compile("^([a-fA-F0-9][:-]){5}[a-fA-F0-9][:-]$");
   Matcher m = p.matcher(mac);
   return m.find();
}

答案 1 :(得分:1)

试试这个,做得很完美..

MAC地址是制造商为识别而分配给大多数网络适配器或网络接口卡(NIC)的唯一标识符,IEEE 802标准使用48个位或6个字节来表示MAC地址。此格式提供了281,474,976,710,656个可能的唯一MAC地址。

IEEE 802标准定义了3种常用格式,以十六进制数字打印MAC地址:

六个由连字符( - )分隔的两个十六进制数字组,如01-23-45-67-89-ab

由冒号(:)分隔的六组两个十六进制数字,如01:23:45:67:89:ab

由点(。)分隔的三组四个十六进制数字,如0123.4567.89ab

public boolean macValidate(String mac) {
        Pattern p = Pattern.compile("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$");
        Matcher m = p.matcher(mac);
        return m.find();
}

答案 2 :(得分:0)

基于AlexR的答案:

private static Pattern patternMacPairs = Pattern.compile("^([a-fA-F0-9]{2}[:\\.-]?){5}[a-fA-F0-9]{2}$");
private static Pattern patternMacTriples = Pattern.compile("^([a-fA-F0-9]{3}[:\\.-]?){3}[a-fA-F0-9]{3}$");

private static boolean isValidMacAddress(String mac)
{
    // Mac addresses usually are 6 * 2 hex nibbles separated by colons,
    // but apparently it is legal to have 4 * 3 hex nibbles as well,
    // and the separators can be any of : or - or . or nothing.
    return (patternMacPairs.matcher(mac).find() || patternMacTriples.matcher(mac).find());
}

这并不完美,因为它会匹配AB:CD.EF-123456之类的东西。如果你想避免这种情况,你可以比我更聪明,让它在每个地方匹配相同的角色,或者只是将两个模式分成一个用于每个可能的分隔符。 (总共六个?)

答案 3 :(得分:0)

我知道这个问题有点旧,但我认为这个问题没有一个非常好的解决方案:

要做的两个步骤

  1. 更改Mac字符串以解析为您选择的格式(例如xx:xx:xx:xx:xx:xx)
  2. 编写一个方法,用于验证上面格式为
  3. 的字符串

    示例:

    1)

    您可以通过调用

    轻松实现此目的
    public static String parseMac(String mac) {
        mac = mac.replaceAll("[:.-]", "");
    
        String res = "";
        for (int i = 0; i < 6; i++) {
            if (i != 5) {
                res += mac.substring(i * 2, (i + 1) * 2) + ":";
            } else {
                res += mac.substring(i * 2);
            }
        }
        return res;
    }
    

    :.-是将从字符串

    中删除的字符

    2)

    public static boolean isMacValid(String mac) {
        Pattern p = Pattern.compile("^([a-fA-F0-9]{2}[:-]){5}[a-fA-F0-9]{2}$");
        Matcher m = p.matcher(mac);
        return m.find();
    }
    

    Ofc,您可以将Pattern设置为本地类变量,以提高代码的效率。

答案 4 :(得分:0)

MAC地址可以是6或20个字节(无限带宽)

假定分隔符为的正确正则表达式为:

^([0-9A-Fa-f]{2}:){5}(([0-9A-Fa-f]{2}:){14})?([0-9A-Fa-f]{2})$

我们匹配XX的5倍:可选地,我们匹配另外XX的14倍:并且我们匹配XX

答案 5 :(得分:0)

可以使用以下代码验证MAC地址:

private static final String PATTERN = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
    
private static boolean validateMAC(String mac) {
        Pattern pattern = Pattern.compile(PATTERN);
        Matcher matcher = pattern.matcher(mac);
        return matcher.matches();
    }

答案 6 :(得分:0)

下面的正则表达式模式将有助于管理上面列出的各种模式

"([MACmac]?){1}([:.-]?){1}(([0-9A-Fa-f]{2,3}[:.-]?){4,6})"

最后我添加了 {4,6} 因为下面要求的一些模式期待 3人一组,共4次。否则,如果您只寻找默认值,通常是 2 个字符组 6 次,那么您可以使用下面的一个。

"([MACmac]?){1}([:.-]?){1}(([0-9A-Fa-f]{2}[:.-]?){6})"

希望这对大家有帮助。