Java 无法全部替换为美元符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9679930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Not able to replace all for dollar sign
提问by Sillicon.Dragons
can anyone advise why i encountered index out of bouns exception when running this method to replace the value by $
sign?
任何人都可以告诉我为什么在运行此方法以按$
符号替换值时遇到 index out of bouns 异常?
E.g. i pass in a message $$vmdomodm$$
例如我传递了一条消息 $$vmdomodm$$
message = message.replaceAll("$", "$");
I tried to look at this forum thread but couldnt understand the content
我试图看这个论坛帖子,但无法理解内容
http://www.coderanch.com/t/383666/java/java/String-replaceAll
http://www.coderanch.com/t/383666/java/java/String-replaceAll
采纳答案by Jigar Joshi
It is special character you need to use escape character
这是您需要使用转义字符的特殊字符
Try with this \\$
试试这个 \\$
and it doesn't make sense in your code you are trying to replacing the content with same
并且在您尝试用相同内容替换内容的代码中没有意义
String message = "$$hello world $$";
message = message.replaceAll("\$", "_");
System.out.println(message);
output
输出
__hello world __
Update
更新
String message = "$hello world $$";
message = message.replaceAll("$", "\$");
System.out.println(message);
output
输出
$hello world $$
回答by anubhava
Since you're not really using any regex so instead of replaceAll you should be using String#replacemethod like this:
由于您并没有真正使用任何正则表达式,因此您应该使用String#replace方法代替 replaceAll,如下所示:
message = message.replace("$", "$");
回答by silverduck
After tinkering around with replaceAll() and never getting what I wanted I figured it would be easier to write a function to escape the dollar signs.
在修改了 replaceAll() 并且从未得到我想要的东西之后,我认为编写一个函数来逃避美元符号会更容易。
public static String escapeDollarSign(String value) {
Pattern p = Pattern.compile("\$");
int off = 0;
while (true) {
Matcher m = p.matcher(value.substring(off));
if (!m.find()) break;
int moff = m.start();
String left = value.substring(0, off+moff);
String right = value.substring(off+moff+1, value.length());
value = left+"\$"+right;
off += moff+1+1;
}
return value;
}
e.g.$re$gex $can $ b$e a$ pain$
becomes\$re\$gex \$can \$ b\$e a\$ pain\$
例如$re$gex $can $ b$e a$ pain$
变成\$re\$gex \$can \$ b\$e a\$ pain\$