Not able to replace all for dollar sign

前端 未结 3 662
耶瑟儿~
耶瑟儿~ 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\$

提交回复
热议问题