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