java格式化mac地址(加分隔符,去分隔符)
專案中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地址,如果不符合規範會丟擲異常
引數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位地址,如果不符合那兩種格式會丟擲異常