Java' String replaceAll to replace overflow at front of string, not end.

Viewed 177

I want to take in a string with dashes. Within the dashes there are groups of characters. That number of characters is specified by an integer K. I'm taking the dashes out to start so I have a clean String then I am using

replaceAll("(.{" + K + "})", "$0-")

To insert a - every K characters. I want the "overflow" (the left over characters after all previous characters were grouped to be put at the front of the string not the end).

For example I have a string with 8 characters:

String s = "1-23456-78";
String newS = s.replace("-", "");

newS is now 12345678

int K = 3; 
String newNewS = newS.replaceAll("(.{" + K + "})", "$0-").trim();

newNewS is 123-456-78

I want it to be 12-345-678. Anyway to reverse the replaceAll method or is there another way to do this?

2 Answers

One simple method I can think of is, you reverse the string and then apply the regex and then reverse again? Check this code.

public static void main(String args[]) {
    String s = "1-23456-78";
    String newS = s.replace("-", "");
    System.out.println(newS);
    int K = 3;
    newS = new StringBuilder(newS).reverse().toString();
    String newNewS = newS.replaceAll("(.{" + K + "})", "$0-").trim();
    System.out.println(new StringBuilder(newNewS).reverse().toString());
}

Let me know if this sounds fine.

You could play with a lookahead (demo):

.{3}(?=(?:.{3})*$)

Replace with:

-$0

In your case:

"12345678".replaceAll(".{" + K + "}(?=(?:.{" + K + "})*$)", "-$0")
Related