emh*_*mha 3 java regex string replace dollar-sign
public static String template = "$A$B"
public static void somemethod() {
template.replaceAll(Matcher.quoteReplacement("$")+"A", "A");
template.replaceAll(Matcher.quoteReplacement("$")+"B", "B");
//throws java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 3
template.replaceAll("\\$A", "A");
template.replaceAll("\\$B", "B");
//the same behavior
template.replace("$A", "A");
template.replace("$B", "B");
//template is still "$A$B"
}
Run Code Online (Sandbox Code Playgroud)
我不明白.我使用了所有可以在互联网上进行替换的方法,包括我可以找到的所有堆栈溢出.我甚至试过了!怎么了?
替换不是在内部完成的(A String不能在Java中修改,它们是不可变的),但是保存在String由方法返回的新内容中.您需要保存返回的String引用,以便发生任何事情,例如:
template = template.replace("$B", "B");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4802 次 |
| 最近记录: |