Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace repeated letters using Regular expression in JAVA

Tags:

java

regex

Suppose I have a string like :

      String s = "hellllooooo howwwwwww areeeeeee youuuuuuu";

I want to discard the repeated letters and want to get :

     "helloo howw aree youu"

I have done the matching using ::

        matches(".*([a-z])\\1{3,}.*"

But how can I replace the helloooooooo to helloo and the others ?

like image 512
Ronin Avatar asked Jan 19 '26 11:01

Ronin


1 Answers

Any of the following produces the result you want:

s = s.replaceAll("([a-z])\\1+", "$1$1");

s = s.replaceAll("(([a-z])\\2)\\2*", "$1");
like image 120
jdb Avatar answered Jan 21 '26 03:01

jdb



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!