Not able to replace all for dollar sign

前端 未结 3 585
耶瑟儿~
耶瑟儿~ 2020-12-03 21:21

can anyone advise why i encountered index out of bouns exception when running this method to replace the value by $ sign?

E.g. i pass in a message

相关标签:
3条回答
  • 2020-12-03 21:57

    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.

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

    0 讨论(0)
  • 2020-12-03 22:04

    Since you're not really using any regex so instead of replaceAll you should be using String#replace method like this:

    message = message.replace("$", "$");
    
    0 讨论(0)
  • 2020-12-03 22:12

    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 $$
    
    0 讨论(0)
提交回复
热议问题