I am having strings like this \"aaaabbbccccaaffffddcfggghhhh\" and i want to remove repeated characters get a string like this \"abcadcfgh\".
A simplistic implementati
You can do this:
"aaaabbbccccaaffffddcfggghhhh".replaceAll("(.)\\1+","$1");
The regex uses backreference and capturing groups.
The normal regex is (.)\1+
but you've to escape the backslash by another backslash in java.
If you want number of repeated characters:
String test = "aaaabbbccccaaffffddcfggghhhh";
System.out.println(test.length() - test.replaceAll("(.)\\1+","$1").length());
Demo
With regex, you can replace (.)\1+
with the replacement string $1
.
You can use Java's String.replaceAll() method to simply do this with a regular expression.
String s = "aaaabbbccccaaffffddcfggghhhh";
System.out.println(s.replaceAll("(.)\\1{1,}", "$1")) //=> "abcadcfgh"
Regular expression
( group and capture to \1:
. any character except \n
) end of \1
\1{1,} what was matched by capture \1 (at least 1 times)
use this pattern /(.)(?=\1)/g
and replace with nothing
Demo