3

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 ");
Cœur
  • 37,241
  • 25
  • 195
  • 267

4 Answers4

4

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();
System.out.println(data);

output:

ab cdef ghij
Pshemo
  • 122,468
  • 25
  • 185
  • 269
2

In C# you would do something like Regex.Replace("1234567890", ".{4}", " $0", RegexOptions.RightToLeft).

Unfortunately, in Java you can't.

As Explossion Pills suggested in a comment, you could reverse the string, apply the regex, and reverse it again.

Another solution could be to take the last N numbers from your string, where N is divisible by 4. Then you can apply the replacement successfully, and concatenate the remaining part of the string at the begining.

Community
  • 1
  • 1
Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
0
String str = "0123456789ABCDE";
// Use a StringBuffer to reverse the string
StringBuffer sb = new StringBuffer(str).reverse();
// This regex causes " " to occur before each instance of four characters
str = sb.toString().replaceAll("....", "$0 ");
// Reverse it again
str = (new StringBuffer(str)).reverse().toString();
System.out.println(str);
corvec
  • 288
  • 4
  • 14
0

For me the best practice was to start from the beginning of the string to the end:

String inputString = "1234123412341234";
int j = 0;
StringBuilder sb = new StringBuilder(inputString);
for (int i = 4; i < kkm.getFiscalNumber().length(); i += 4) {
    sb.insert(i + j, ' ');
    j++;
}
String result = sb.toString(); // 1234 1234 1234 1234
Alex Tuhlom
  • 61
  • 2
  • 5