如何用允许的最大出现次数替换字符的多个连续出现? [英] How to replace multiple consecutive occurrences of a character with a maximum allowed number of occurences?

查看:49
本文介绍了如何用允许的最大出现次数替换字符的多个连续出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CharSequence content = new StringBuffer("aaabbbccaaa");
String pattern = "([a-zA-Z])\\1\\1+";
String replace = "-";

Pattern patt = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = patt.matcher(content);

boolean isMatch = matcher.find();
StringBuffer buffer = new StringBuffer();

for (int i = 0; i < content.length(); i++) {
    while (matcher.find()) {
        matcher.appendReplacement(buffer, replace);
    }
}
matcher.appendTail(buffer);
System.out.println(buffer.toString());

在上面的代码中, content 是输入字符串,

In the above code content is input string,

我正在尝试从字符串中查找重复出现的内容,并希望将其替换为最大出现次数

I am trying to find repetitive occurrences from string and want to replace it with max no of occurrences

例如

输入-("abaaadccc",2)
输出-"abaadcc"
这里 aaa ccc aa cc 代替,因为允许的最大重复数是 2

input -("abaaadccc",2)
output - "abaadcc"
here aaaand cccis replced by aa and cc as max allowed repitation is 2

在上面的代码中,我发现了这种情况,并尝试用-替换它们,但是它可以工作,但是有人可以帮助我如何获取当前的char并替换为允许的情况

In the above code, I found such occurrences and tried replacing them with -, it's working, But can someone help me How can I get current char and replace with allowed occurrences

即,如果找到 aaa ,则将其替换为 aa

i.e If aaa is found it is replaced by aa

还是没有其他使用正则表达式的方法?

or is there any alternative method w/o using regex?

推荐答案

您可以在正则表达式中声明第二个组并将其用作替代:

You can declare the second group in a regex and use it as a replacement:

String result = "aaabbbccaaa".replaceAll("(([a-zA-Z])\\2)\\2+", "$1");

这是它的工作方式:

(                        first group - a character repeated two times
    ([a-zA-Z])           second group - a character
    \2                   a character repeated once
)                        
\2+                      a character repeated at least once more

因此,第一组捕获替换字符串.

Thus, the first group captures a replacement string.

不难推断此解决方案的最大允许重复次数的最大值:

It isn't hard to extrapolate this solution for a different maximum value of allowed repeats:

String input = "aaaaabbcccccaaa";
int maxRepeats = 4;
String pattern = String.format("(([a-zA-Z])\\2{%s})\\2+", maxRepeats-1);
String result = input.replaceAll(pattern, "$1");
System.out.println(result); //aaaabbccccaaa

这篇关于如何用允许的最大出现次数替换字符的多个连续出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆