Paul Sender :
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?
sp00m :
You could play with a lookahead (demo):
.{3}(?=(?:.{3})*$)
Replace with:
-$0
In your case:
"12345678".replaceAll(".{" + K + "}(?=(?:.{" + K + "})*$)", "-$0")