Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a series of substrings by one copy

Tags:

java

regex

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

like image 993
mossaab Avatar asked Feb 20 '23 05:02

mossaab


1 Answers

    String[] terms = { "Bahhhhhhh", "Bahahahaha" };
    for (String term : terms) {
        System.out.println(term.replaceAll("(.+?)\\1{2,}", "$1"));
    }

Output:

Bah 
Baha
like image 185
Prince John Wesley Avatar answered Feb 22 '23 22:02

Prince John Wesley