匹配 MAC 地址的正确正则表达式是什么?我对此进行了谷歌搜索,但是大多数问题和答案都不完整。它们只提供了一个正则表达式, 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 :.
但是,这不是现实世界的情况。许多路由器、交换机和其他网络设备供应商提供以下格式的 MAC 地址:
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
直到现在我所拥有的是:
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);
}
}
}
如何在代码中结合这两个正则表达式?