用正则表达式替换多个字符的数量

时间:2014-11-06 17:13:22

标签: java regex replace

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

上面的示例应编码为" 4aff4d"

3 个答案:

答案 0 :(得分:0)

这并不容易,因为你无法轻易获得替换部分中的#匹配。试试这段代码:

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

答案 1 :(得分:0)

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

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);

答案 2 :(得分:0)

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