匹配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
Run Code Online (Sandbox Code Playgroud)
直到这一刻我才拥有的是:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你如何在代码中结合两个正则表达式?
为什么这么多代码?以下是如何"规范化"您的mac地址:
mac.replaceAll("[^a-fA-F0-9]", "");
以下是验证它的方法:
public boolean validate(String mac) {
Pattern p = Pattern.compile("^([a-fA-F0-9][:-]){5}[a-fA-F0-9][:-]$");
Matcher m = p.matcher(mac);
return m.find();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11321 次 |
| 最近记录: |