简体   繁体   中英

most elegant way of escaping $ in java

I have a base String "abc def" , I am trying to replace my base string with "abc$ def$" using replaceFirst() , which is running into errors as $ is not escaped.

I tried doing it with Pattern and Matcher APIs, as given below,

newValue = "abc$ def$";

if(newValue.contains("$")){
    Pattern specialCharacters = Pattern.compile("$");
    Matcher newMatcherValue = specialCharacters.matcher(newValue) ;
    newValue = newMatcherValue.replaceAll("\\\\$") ;
}

This runs into an error. Is there any elegant way of replacing my second string "abc$ def$" with "abc\\\\\\\\$ def\\\\\\\\$" so as to use the replacefirst() API successfully?

Look at Pattern.quote() to quote a regex and Matcher.quoteReplacement() to quote a replacement string.

That said, does this do what you want it to?

System.out.println("abc def".replaceAll("([\\w]+)\\b", "$1\\$"));

This prints out abc$ def$

You can use replaceAll just in one step:

String newValueScaped = newValue.replaceAll("\\$", "\\\\$")

$ has a special mining in regex, so you need to scape it. It's used to match the end of the data.

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