用唯一替换替换字符串中的所有实例

时间:2014-08-01 13:44:00

标签: java regex string

我尝试用唯一替换替换特定String的所有实例。

我想要的是什么:

如果我有这个字符串:

String testScript = "while(true) { } while   (10 < 7) { } while((10 < 7)) { }";

我想要这个输出:

while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }

我有什么:

但是,传递给replaceAll的字符串不会再次被查询(现在我很清楚)。

while(arg0 < 5000 && true) { } while(arg0 < 5000 && 10 < 7) { } while(arg0 < 5000 && (10 < 7)){ }

我们非常感谢任何答案或评论。

SSCCE:

public static void main(String[] args) {
     int counter = 0;
     String testScript = "while(true) { } while   (10 < 7) { } while((10 < 7)) { }";
     String out = testScript.replaceAll("while\\s*\\(", "while(arg" + (counter++) + " < 5000 && ");
     System.out.println(out);
}

1 个答案:

答案 0 :(得分:4)

您似乎正在寻找appendReplacement课程中的appendTailMatcher方法。

这两种方法都需要临时缓冲区,其中将放置新的(替换)版本的字符串。在这种情况下,使用了StringBuffer

他们的目的是添加到已修改文本的缓冲区块

  • appendReplacement(StringBuffer sb, String replacement)当匹配时将找到上次匹配的文本(或者从字符串开头的第一次匹配)到当前匹配+替换的开始
  • appendTail(StringBuffer sb)当没有匹配时,我们还需要在最后一场比赛后添加文字(或者如果没有匹配整个原始字符串)。

换句话说,如果您有文字xxxxfooxxxxxfooxxxx并且想要将foo替换为bar,则匹配器需要调用

                       xxxxfooxxxxxfooxxxx
1. appendReplacement   ^^^^^^^              will add to buffer xxxxbar
1. appendReplacement          ^^^^^^^^      will add to buffer xxxxxbar
3. appendTail                         ^^^^  will add to buffer xxxx

所以在此缓冲区之后将包含xxxxbarxxxxxbarxxxx

演示

String testScript = "while(true) { } while   (10 < 7) { } while((10 < 7)) { }";
Pattern p = Pattern.compile("while\\s*\\(");
Matcher m = p.matcher(testScript);

int counter = 0;
StringBuffer sb = new StringBuffer();

while(m.find()){
    m.appendReplacement(sb, "while(arg"+ (counter++) + " < 5000 && ");
}
m.appendTail(sb);

String result = sb.toString();
System.out.println(result);

输出:

while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }
相关问题