Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive replaceAll java [duplicate]

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.

like image 573
Mayday Avatar asked Apr 07 '16 11:04

Mayday


2 Answers

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"
like image 91
Jon Skeet Avatar answered Nov 15 '22 22:11

Jon Skeet


You can do it without recursion. The regular expression "(.)\\1+" will capture every character followed by themselves at least once, and it replaces them with the captured character. Thus, this removes any repeated characters.

public static void main(String[] args) {
    String str = "aaaabbbaaa";
    String result = str.replaceAll("(.)\\1+", "$1");
    System.out.println(result); // prints "aba".
}

With this, it works for all characters.

like image 31
Tunaki Avatar answered Nov 15 '22 21:11

Tunaki