Replace a row of substrings with one copy

For this word, I want to look for all the substrings that appear next to each other at least 3 times, and replace all of them with only one. I know how to do this when a substring is just one character. For example, the code below returns "Bah" for the input string "Bahhhhhhh":

String term = "Bahhhhhhh"; term = term.replaceAll("(.)\\1{2,}", "$1"); 

However, I need a more general template that turns Bahahahaha into Baha.

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

Conclusion:

 Bah Baha 
+6
source

This will work for repetitions of 1, 2 or 3 characters in length.

 String term = "Bahhhhhhh"; term = term.replaceAll("(.{1,3})\\1{2,}", "$1"); 

You need to be careful to avoid huge backtracking performance impacts . So I limited it to 1-3 characters.

+2
source

Source: https://habr.com/ru/post/1416602/


All Articles