Dejell
Dejell

Reputation: 14317

how to replace \$ with $ in regex java

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

Answers (4)

RokL
RokL

Reputation: 2812

Either use direct string replacement:

valueExpression.replace("\\$", "$");

or you need to escape group reference in the replacement string:

valueExpression.replaceAll("\\$", "\\$");

Upvotes: 0

Qtax
Qtax

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

Pshemo
Pshemo

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

user432
user432

Reputation: 3534

valueExpression.replaceAll("\\\\[$]", "\\$"); should achieve what you are looking for.

Upvotes: 3

Related Questions