How do I validate the format of a MAC address?

前端 未结 11 1480
逝去的感伤
逝去的感伤 2020-12-15 05:59

What\'s the best way to validate that an MAC address entered by the user?

The format is HH:HH:HH:HH:HH:HH, where each H is a hexadecimal ch

11条回答
  •  爱一瞬间的悲伤
    2020-12-15 07:03

    This Regex validates the following MAC format

    "Ae:Bd:00:00:00:00"
    "00-00-00-00-00-00"
    "aaaa.bbbb.cccc"
    
    private static final String MAC_PATTERN = "(([0-9A-Fa-f]{2}[-:.]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})";
    
    public class MacRegExp {
    
        private static final String MAC_PATTERN = "(([0-9A-Fa-f]{2}[-:.]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})";
    
        static boolean validateMAC(final String mac){          
            Pattern pattern = Pattern.compile(MAC_PATTERN);
            Matcher matcher = pattern.matcher(mac);
            return matcher.matches();             
        }
    
    }
    

    Hope this helps

提交回复
热议问题