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 ");
3
  • 4
    Why don't you just reverse the string before operating on it? Commented Feb 14, 2013 at 0:52
  • That had crossed my mind, but I am not very familiar with Regex and I was not sure if there was an option to do this. Commented Feb 14, 2013 at 1:04
  • @A_Kiniyalocts I don't there is one. Commented Feb 14, 2013 at 1:05

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

I personally recommend the StringBuilder solution for problems of this nature.
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.

Comments

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);

1 Comment

Thanks, this also works great. Thanks for explaining it step by step too.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.