A_Kiniyalocts A_Kiniyalocts - 5 months ago 44
Java Question

Regex for formatting binary number with spaces every 4 characters, from right to left in Java

I'm writing a binary/decimal/hexadecimal converter for Android and am trying to format a String in Java with a regex that will add a space to every four characters from right to left.

This code works from left to right, but I am wondering if there is a way I can reverse it.

stringNum = stringNum.replaceAll("....", "$0 ");

Answer Source

Maybe instead of regex use StringBuilder like this

String data = "abcdefghij";
StringBuilder sb = new StringBuilder(data);
for (int i = sb.length() - 4; i > 0; i -= 4)
    sb.insert(i, ' ');
data = sb.toString();


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