Different MAC Addresses Regex

后端 未结 7 843
旧时难觅i
旧时难觅i 2021-01-06 08:30

What is the correct regular expression for matching MAC addresses ? I googled about that but, most of questions and answers are incomplete. They only provide a regular expre

7条回答
  •  庸人自扰
    2021-01-06 09:03

    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

    Example:

    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)

    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.

提交回复
热议问题