Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 898
Paul Sender Avatar asked Feb 24 '26 06:02

Paul Sender


1 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.

like image 199
Pushpesh Kumar Rajwanshi Avatar answered Feb 26 '26 22:02

Pushpesh Kumar Rajwanshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!