我想知道在Java中将字符串“00155D038D01”转换为macAdress格式的最简单方法。
答案 0 :(得分:12)
尝试使用正则表达式
char divisionChar = ':';//change to '-' if you want your mac to be like 00-15-5D-03-8D-01
String unformattedMAC = "00155D038D01";
String formattedMAC = unformattedMAC.replaceAll("(.{2})", "$1"+divisionChar).substring(0,17);
适用于您拥有的所有MAC地址
答案 1 :(得分:7)
显然,
public String convertToMacAddress(String input) {
if (input.equals("00155D038D01") {
return "00-15-5D-03-8D-01";
}
return null;
}
答案 2 :(得分:4)
我会说"00155D038D01".replaceAll("(..)(?!$)", "$1-")
是最简单的:)
答案 3 :(得分:1)
直截了当的方式:
String s = "00155D038D01";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length();)
{
sb.append(s.substring(i++, ++i));
if(i < s.length()) sb.append("-");
}
String mac = sb.toString();
答案 4 :(得分:1)
String address = "00155D038D01";
StringBuilder sb = new StringBuilder(address);
for(int i = 2; i < address.length()+(i/3); i+=3){
sb.insert(i, ':');
}
System.out.println(sb.toString());