java格式化mac地址,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位地址,如果不符合那两种格式会抛出异常

都是static的,粘到自己utils类下就能直接用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值