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