Reputation: 14317
I have the following String
String valueExpression = "value1\\$\\$bla";
i would like it to be parsed to:
value1$$bla
when I try to do:
valueExpression.replaceAll("\\\\$", "\\$");
I get it the same, and when I try to do:
valueExpression.replaceAll("\\$", "$");
I get an error IndexOutOfBound
How can I replace it in regex?
The string is dynamic so I can't change the content of the string valueExpression to something static.
Thanks
Upvotes: 2
Views: 558
Reputation: 2812
Either use direct string replacement:
valueExpression.replace("\\$", "$");
or you need to escape group reference in the replacement string:
valueExpression.replaceAll("\\$", "\\$");
Upvotes: 0
Reputation: 33908
You want a string containing \\\$
(double backslash to get a literal backslash, and a backslash to escape the $
). To write that quoted as a string in Java you should escape each backslash with another backslash. So you would write that as "\\\\\\$"
.
Ie.
valueExpression.replaceAll("\\\\\\$", "\\$");
Upvotes: 0
Reputation: 124215
Simplest approach seems to be
valueExpression.replace("\\$", "$")
which is similar to
valueExpression.replaceAll(Pattern.quote("\\$"), Matcher.quoteReplacement("$"))
which means that it automatically escapes all regex matacharacters from both parts (target and replacement) letting you use simple literals.
BTW lets not forget that String is immutable so its methods like replace
can't change its state (can't change characters it stores) but will create new String with replaced characters.
So you want to use
valueExpression = valueExpression.replace("\\$", "$");
Example:
String valueExpression = "value1\\$\\$bla";
System.out.println(valueExpression.replace("\\$", "$"));
output: value1$$bla
Upvotes: 3
Reputation: 3534
valueExpression.replaceAll("\\\\[$]", "\\$");
should achieve what you are looking for.
Upvotes: 3