Search code examples
javastringreplaceall

Splitting string into parts with .replaceAll function from opposite direction? JAVA


Let's say I have the following string in JAVA:

str = "B49FD7FD96B"

I can change this string into B49F D7FD 96B by doing the following:

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

But how can I change my string into this??? B49 FD7F D96B

So in a way I actually need to use the function .ReplaceAll() from the opposite direction. Or is this not possible with .ReplaceAll() and do I need to use something else? If so, what would be the best way to do this?


Solution

  • If you want to split it into groups of 4 with the leftovers at the beginning instead of the end by using replaceAll "the other way," you can just reverse the string, do it, and reverse it again:

    str = "B49FD7FD96B";
    str = new StringBuilder(str).reverse().toString();
    str = str.replaceAll("....",  "$0 ");
    str = new StringBuilder(str).reverse().toString();
    

    Result: "B49 FD7F D96B"