項目中MAC地址經常需要格式化靶壮,有的需要分隔符,有的不需要分隔符员萍,比較煩腾降。自己實現了這兩個方法,大佬輕噴
1碎绎、類似12ae5bac34c4中間無分隔符螃壤,需要在中間加入分隔符(:或者-),最終效果:12:ae:5b:ac:34:c4
方法:
public static String formatMac(String mac, String split) {
String regex = "[0-9a-fA-F]{12}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(mac);
if (!matcher.matches()) {
throw new IllegalArgumentException("mac format is error");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 12; i++) {
char c = mac.charAt(i);
sb.append(c);
if ((i & 1) == 1 && i <= 9) {
sb.append(split);
}
}
return sb.toString();
}
參數mac是無分隔符的12位mac地址,如果不符合規(guī)范會拋出異常
參數split是你需要的分隔符
2筋帖、類似12:ae:5b:ac:34:c4或者12-ae-5b-ac-34-c4中間有分隔符奸晴,需要去掉分隔符(:或者-),最終效果:12ae5bac34c4
方法:
public static String formatMac1(String mac) {
String regex = "(([a-f0-9]{2}:)|([a-f0-9]{2}-)){5}[a-f0-9]{2}";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(mac);
if (!matcher.matches()) {
throw new IllegalArgumentException("mac format is error");
}
return mac.replaceAll("[:-]", "");
}
參數mac是有分隔符17位地址,如果不符合那兩種格式會拋出異常