JMBise JMBise - 1 year ago 161
Java Question

Add colons to mac address using regex

I have a mac address looking like this

and I want to return it into something like this

I have been able to make this code:


However it returns
instead of
I would like to ignore the last match to avoid having the last :

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download