java 不同的 MAC 地址正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16829485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:06:47  来源:igfitidea点击:

Different MAC Addresses Regex

javaregex

提问by Adelin

What is the correct regular expression for matching MAC addresses ? I googled about that but, most of questions and answersare incomplete. They only provide a regular expression for 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 :.However, this is not the real world case. Many routers, switches and other network devices vendors provide MAC addresses in formats like :

匹配 MAC 地址的正确正则表达式是什么?我用谷歌搜索了一下,但大多数问题和答案都不完整。他们只提供了一个正则表达式, 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 :.但是,这不是现实世界的情况。许多路由器、交换机和其他网络设备供应商以如下格式提供 MAC 地址:

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

What I have until this moment is this:

直到这一刻我所拥有的是:

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);
    }

  }
}

How do yo combine the two regex in the code ?

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

回答by AlexR

Why so much code? Here is how you can "normalize" your mac address:

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

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

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

And here is a way to validate it:

这是一种验证它的方法:

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();
}

回答by Neeraj Singh

Try this, working perfect..

试试这个,完美运行..

A MAC address is a unique identifier assigned to most network adapters or network interface cards (NICs) by the manufacturer for identification, IEEE 802 standards use 48 bites or 6 bytes to represent a MAC address. This format gives 281,474,976,710,656 possible unique MAC addresses.

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

IEEE 802 standards define 3 commonly used formats to print a MAC address in hexadecimal digits:

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

Six groups of two hexadecimal digits separated by hyphens (-), like 01-23-45-67-89-ab

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

Six groups of two hexadecimal digits separated by colons (:), like 01:23:45:67:89:ab

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

Three groups of four hexadecimal digits separated by dots (.), like 0123.4567.89ab

三组由点 (.) 分隔的四个十六进制数字,如 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();
}

回答by Olivier LAHAYE

MAC addresses can be 6 or 20 bytes (infiniband)

MAC 地址可以是 6 或 20 个字节(infiniband)

The correct regexp assuming the separator is : is

假设分隔符的正确正则表达式是:是

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

We match 5 times XX: optionally we match another 14 times XX: and we match XX

我们匹配 5 次 XX:可选地我们匹配另外 14 次 XX:我们匹配 XX

回答by benkc

Based on AlexR's answer:

基于 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());
}

This isn't quite perfect, as it will match something like AB:CD.EF-123456. If you want to avoid that, you can either get more clever than I with making it match the same character in each place, or just split the two patterns into one for each possible separator. (Six total?)

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

回答by codewing

I know this question is kind of old but i think there is not a really good solution for the problem:

我知道这个问题有点老了,但我认为这个问题没有一个很好的解决方案:

Two steps to do

两步做

  1. Change the Mac String to parse to the format of your choice (e.g. xx:xx:xx:xx:xx:xx)
  2. Write a method which validates a string with the format above
  1. 更改 Mac 字符串以解析为您选择的格式(例如 xx:xx:xx:xx:xx:xx)
  2. 编写一个方法来验证具有上述格式的字符串


Example:

例子:

1)

1)

you can easily achieve this by calling

您可以通过调用轻松实现此目的

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;
}

:.- are the chars which will be removed from the string

:.- 是将从字符串中删除的字符

2)

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 you can make the Pattern a local class variable to improve the efficiency of your code.

Ofc 你可以让 Pattern 成为一个局部类变量来提高你的代码效率。