JMBise JMBise - 2 months ago 11
Java Question

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


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 :

Answer

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:")).

Comments