문제

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 ?

도움이 되었습니까?

해결책

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

다른 팁

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,})", ""));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top