开发者

Java String: Replace a string containing $ sign

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜