简体   繁体   中英

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", "REPLACED"));

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

尝试

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

You Can Simply use this method:

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

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

Java API文档 :“请注意,替换字符串中的反斜杠()和美元符号($)可能导致结果与将其视为文字替换字符串时的结果不同;请参阅Matcher.replaceAll。使用Matcher.quoteReplacement( java.lang.String)如果需要,可以抑制这些字符的特殊含义。“

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"));

或者,让正则表达式库为您处理:

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

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