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
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\$
Since you're not really using any regex so instead of replaceAll you should be using String#replace method like this:
message = message.replace("$", "$");
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 $$