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.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With