简体   繁体   English

使用正则表达式将冒号添加到 mac 地址

[英]Add colons to mac address using regex

I have a mac address looking like this 482C6A1E593D and I want to return it into something like this 48:2C:6A:1E:59:3D我有一个类似482C6A1E593D的 mac 地址,我想将其返回到类似48:2C:6A:1E:59:3D

I have been able to make this code:我已经能够制作这个代码:

Pattern.compile("(.{2})").matcher(macAddress).replaceAll("$1:");

However it returns 48:2C:6A:1E:59:3D: instead of 48:2C:6A:1E:59:3D I would like to ignore the last match to avoid having the last :但是它返回48:2C:6A:1E:59:3D:而不是48:2C:6A:1E:59:3D我想忽略最后一场比赛以避免最后一场比赛:

You should use a negative look head for end of String.您应该对字符串的结尾使用否定的查找头。

public static void main(String[] args) {
    String s = "482C6A1E593D";
    s = s.replaceAll("(\\w{2})(?!$)", "$1:");
    System.out.println(s);
}

O/P :开/关:

48:2C:6A:1E:59:3D

You may also use a positive lookahead requiring a symbol to be present:您还可以使用需要存在符号的正向前瞻:

String macAddress = "482C6A1E593D";
System.out.println(macAddress.replaceAll(".{2}(?=.)", "$0:"));

See this demo这个演示

Note you do not need any capturing groups here since $0 is a backreference to the whole match (same can be used with TheLostMind's regex - use s.replaceAll("\\\\w{2}(?!$)", "$0:") ).请注意,这里不需要任何捕获组,因为$0是对整个匹配项的反向引用(同样可以与TheLostMind 的正则表达式一起使用 - 使用s.replaceAll("\\\\w{2}(?!$)", "$0:") )。

Kotlin version of Wiktor Stribiżew 's answer: Kotlin版本的Wiktor Stribiżew的回答:

val macAddress = "482C6A1E593D"
println(macAddress.replace(".{2}(?=.)".toRegex(), "$0:"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM