Search code examples
javareplaceall

Remove all two or more consecutive A's from a string using replaceAll()


I want to remove all two or more consecutive A's from a string.

i.e, if input is AAAAAAABBABBCACBAAZASCAAA

output should be BBABBCACBZASC.

And what I tried is,

String k = "AAAAAAABBABBCACBAAZASCAAA";
System.out.println(k.replaceAll("(AA)+", "-").replaceAll("-A","").replaceAll("-", ""));

It works fine. But if the string contains - , it makes problem. How can i resolve it ?


Solution

  • k.replaceAll("A{2,}", "-"); is the pattern you want