Recursive replaceAll java

I am trying to replace all the repeated characters from a String in Java, and let only one.

For example:

aaaaa ---> a

For that, I have tried using the replaceAll method:

"aaaaa".replaceAll("a*","a") //returns "aa"

I have developed a recursive method, which is probably not very efficient:

public String recursiveReplaceAll(String original,String regex, String replacement) {
    if (original.equals(original.replaceAll(regex, replacement))) return original;
    return recursiveReplaceAll(original.replaceAll(regex, replacement),regex,replacement);
}

This method works, I was just wondering if there was anything using RegEx for example, which does the work with better performance.

Jon Skeet
people
quotationmark

Your replaceAll approach was nearly right - it's just that * matches 0 occurrences. You want + to mean "one or more".

"aaaaa".replaceAll("a+","a") // Returns "a"

people

See more on this question at Stackoverflow