【问题标题】:How to replace multiple consecutive occurrences of a character with a maximum allowed number of occurences?如何用最大允许出现次数替换多个连续出现的字符?
【发布时间】:2019-07-16 17:20:13
【问题描述】:
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是输入字符串,

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

举例

输入-("abaaadccc",2)
输出 - "abaadcc"
这里aaacccaacc替换,因为最大允许重复是2

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

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

或者有没有使用正则表达式的替代方法?

【问题讨论】:

    标签: java regex string


    【解决方案1】:

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

    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
    

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

    不难将这个解决方案推断为允许重复的不同最大值:

    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
    

    【讨论】:

      【解决方案2】:

      由于您在正则表达式中定义了一个组,您可以通过调用matcher.group(1) 来获取该组的匹配字符。在您的情况下,它包含重复组中的第一个字符,因此通过将其附加两次,您可以获得预期的结果。

          CharSequence content = new StringBuffer("aaabbbccaaa");
          String pattern = "([a-zA-Z])\\1\\1+";
      
          Pattern patt = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
          Matcher matcher = patt.matcher(content);
      
          StringBuffer buffer = new StringBuffer();
      
          while (matcher.find()) {
              System.out.println("found : "+matcher.start()+","+matcher.end()+":"+matcher.group(1));
              matcher.appendReplacement(buffer, matcher.group(1)+matcher.group(1));
          }
          matcher.appendTail(buffer);
          System.out.println(buffer.toString());
      

      输出:

      found : 0,3:a
      found : 3,6:b
      found : 8,11:a
      aabbccaa
      

      【讨论】:

        猜你喜欢
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多