Different MAC Addresses Regex

后端 未结 7 786
旧时难觅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:23

    Based on AlexR's answer:

    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?)

    0 讨论(0)
提交回复
热议问题