Recursive replaceAll java

I am trying to replace all duplicate characters from String in Java and allow only one.

For example:

aaaaa ---> a

For this, I tried using the replaceAll method:

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

I developed a recursive method that 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'm just wondering if there is anything using RegEx, for example, that does the job with better performance.

+7
java regex recursion
source share
2 answers

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

 "aaaaa".replaceAll("a+","a") // Returns "a" 
+12
source share

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

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

However, it works for all characters.

+7
source share

All Articles