k.replaceAll("A{2,}", "-");
is the pattern you want
Remove all two or more consecutive A's from a string using replaceAll()
-
22-09-2022 - |
Question
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
OTHER TIPS
You only need one replaceAll step, if you use the following:
String original = "AAAAAAABBABBCACBAAZASCAAA";
String replaced = original.replaceAll("A{2,}", "");
// assertEquals("BBABBCACBZASC",replaced);
Your regexp only matches an even number of *A*s, this is why you had to use the additional replaceAll steps to succeed. What you really want is, to replace two or more consecutive *A*s with "". In regexp, this requires the use of the correct quantifier, as explained in the Quantifiers tutorial. In your case: A{2,}
.
String k = "AAAAAAABBABBCACBAAZASCAAA";
System.out.println(k.replaceAll("(A{2,})", ""));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow