开发者

Java String: Replace a string containing $ sign

开发者 https://www.devze.com 2023-02-01 20:07 出处:网络
How can I replace a String $1 in Java? I tried this, but this doesn\'t replace it: System.out.println(someHTMLCodeAsString.replaceAll(\"$1\", \"开发者_StackOverflowREPLACED\"));

How can I replace a String $1 in Java? I tried this, but this doesn't replace it:

System.out.println(someHTMLCodeAsString.replaceAll("$1", "开发者_StackOverflowREPLACED"));


The $ is being interpreted as regex instead of as a character (it means 'end of line'). Try System.out.println(someHTMLCodeAsString.replaceAll("\\$1", "REPLACED"));


try

 System.out.println(someHTMLCodeAsString.replace("$1", "REPLACED"));


You've gotten bits and pieces of a response. Peter Lawrey is correct. You need to escape the $ with a regex escape not a string escape, thus the double \.

System.out.println(someHTMLCodeAsString.replaceAll("\\$1", "REPLACED"));


Or, let the regex library handle it for you:

someHTMLCodeAsString.replaceAll(Pattern.quote("$1"), "REPLACED")


You Can Simply use this method:

someHTMLCodeAsString.replaceAll("\\$1", "REPLACED").

That replace All "$" to "REPLACED" simply!


From Java API docs: "Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired."

0

精彩评论

暂无评论...
验证码 换一张
取 消