简体   繁体   English

无法全部替换为美元符号

[英]Not able to replace all for dollar sign

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 异常?

Eg 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

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 $$

由于您并没有真正使用任何正则表达式,因此您应该使用String#replace方法代替 replaceAll,如下所示:

message = message.replace("$", "$");

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

eg例如
$re$gex $can $ b$ea$ pain$
becomes变成
\\$re\\$gex \\$can \\$ b\\$ea\\$ pain\\$

if(!str.isempty() && str.contains("$")){
   str = str.replaceAll("\\$", Matcher.quoteReplacement("\\$"))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM