For a given word, I want to search for all the substrings that appear next to each other at least 3 times, and replace all of them by only one. I know how to do this when the substring is only one character. For instance, the code below returns "Bah" for the input string "Bahhhhhhh":
String term = "Bahhhhhhh";
term = term.replaceAll("(.)\\1{2,}", "$1");
However, I need a more generic pattern that converts "Bahahahaha" into "Baha".
String[] terms = { "Bahhhhhhh", "Bahahahaha" };
for (String term : terms) {
System.out.println(term.replaceAll("(.+?)\\1{2,}", "$1"));
}
Bah
Baha
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With