简体   繁体   English

使用replaceAll()从字符串中删除所有两个或多个连续的A

[英]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. 我想从字符串中删除所有两个或多个连续的A

ie, if input is AAAAAAABBABBCACBAAZASCAAA 即,如果输入为AAAAAAABBABBCACBAAZASCAAA

output should be BBABBCACBZASC . 输出应为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 是你想要的模式

String k = "AAAAAAABBABBCACBAAZASCAAA";
System.out.println(k.replaceAll("(A{2,})", ""));

You only need one replaceAll step, if you use the following: 如果使用以下命令,则只需要一个replaceAll步骤:

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. 您的正则表达式仅匹配偶数个 * A *,这就是为什么您必须使用附加的replaceAll步骤才能成功的原因。 What you really want is, to replace two or more consecutive *A*s with "". 您真正想要的是用“”替换两个或多个连续的 * A *。 In regexp, this requires the use of the correct quantifier, as explained in the Quantifiers tutorial . 在regexp中,这需要使用正确的量词,如Quantifiers教程中所述 In your case: A{2,} . 在您的情况下: A{2,}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM