简体   繁体   中英

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

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

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

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("\\\\\\$", "\\$");

Either use direct string replacement:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM