Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove only leading repeating characters if occurs more than 4 times in string

Tags:

java

string

regex

The repeating characters can be anything [a to z], [0 to 9] or any special characters.

For example:

String a = "CCCCCCgshdbuasvbd";

Consider C = [a to z],[0 to 9], or anything like ~!@#$%*&()_-><?.

I need to remove the "any repeating leading characters in string if that occurs more than 4 times" in the string.

How can I accomplish this using a regex?

like image 389
user3726188 Avatar asked Dec 14 '25 13:12

user3726188


2 Answers

You can use:

str = str.replaceAll("^(\\S)\\1{3,}", "");

Working Demo

like image 110
anubhava Avatar answered Dec 17 '25 03:12

anubhava


How about:

Search: ^(.)\1{3,}
Replace: <NOTHING>

This will replace any character at the beginning of the string, present 4 or more times, by nothing.

like image 27
Toto Avatar answered Dec 17 '25 02:12

Toto