首页 > 解决方案 > Java RegEx doesn't replaceAll

问题描述

I was trying to replace concatenation symbol '+' with '||' in given multi-line script, however it seems that java regex just replaces 1 occurrence, instead of all.

String ss="A+B+C+D";
Matcher mm=Pattern.compile("(?imc)(.+)\\s*\\+\\s*(.+)").matcher(ss);

while(mm.find())
{
    System.out.println(mm.group(1));
    System.out.println(mm.group(2));
    ss=mm.replaceAll("$1 \\|\\| $2");
}

System.out.println(ss); // Output: A+B+C||D, Expected: A||B||C||D

标签: javaregex

解决方案


You could just use:

ss = ss.replaceAll("\\+", "||")

as @ernest_k has pointed out. If you really want to continue using a matcher with iteration, then use Matcher#appendReplacement with a StringBuffer:

String ss = "A+B+C+D";
Matcher mm = Pattern.compile("\\+").matcher(ss);

StringBuffer sb = new StringBuffer();

while (mm.find()) {
    mm.appendReplacement(sb, "||");
}
mm.appendTail(sb);

System.out.println(sb);

推荐阅读