【问题标题】:Replace multiple characters by their quantity with regex用正则表达式按数量替换多个字符
【发布时间】:2014-11-06 17:13:21
【问题描述】:

我有一个可能看起来像这样的字符串:“aaaaffdddd”,并且想用 [NUMBER_OF_CHARACTERS][ONE_TIME_THE_CHARACTER] 替换出现 3 次(或更多)的字符 - 我对 RegEx 不是很有信心,但我来了加上 "([A-z])(\1{2,})" 来准确地找到那些。但是,在 javas String.replaceAll() 中,我无法引用组中的字符数(?),如果我使用 Matcher.appendReplace() 和 StringBuffer,我会丢失字符串的其余部分,因为结果应该仍然包括不出现 3 次或更多次的字符。

上面的例子应该编码为“4aff4d”

【问题讨论】:

  • 那你没有正确使用Matcher.appendReplace()。您必须将它与findappendTail 一起使用,如果使用正确,它将复制源字符串的不匹配部分。查看API documentation 获取完整示例。
  • 是的,这确实是我的问题,我在替换完所有匹配项后添加了 appendTail 并且有效。

标签: java regex replace


【解决方案1】:

这并不容易,因为您无法轻松获得替换零件中的匹配数。试试这个代码:

Pattern pat = Pattern.compile("(?i)([A-Z])(?=\\1{2})");
String str = "aaaaffdddd";
Matcher mat = pat.matcher(str);
Map<String, Integer> charMap = new HashMap<>();
while(mat.find()) {
    String key = mat.group();
    if (!charMap.containsKey(key))
        charMap.put(key, 3);
    else
        charMap.put(key, charMap.get(key)+1);
}
System.out.println("map " + charMap);
for (Entry<String, Integer> e: charMap.entrySet()) {
    str = str.replaceAll(e.getKey() + "+", e.getValue() + e.getKey());
}
System.out.println(str);

输出:

map {d=4, a=4}
4aff4d

【讨论】:

    【解决方案2】:

    你可以试试这个(未测试)

    String str = "aaaaffdddd";
    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile("([A-z])(\\1{2,})");
    Matcher m = p.matcher(str);
    while (m.find()) {
      m.appendReplacement(sb, "" + (m.group(2).length() + 1) + m.group(1));
    }
    System.out.println(sb);
    

    【讨论】:

      【解决方案3】:

      在 StringBuffer 上使用 appendReplacement 后,我​​不得不调用 appendTail 来重建字符串的其余部分。感谢 Holger 的建议!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多