简体   繁体   English

Java String:替换包含$ sign的字符串

[英]Java String: Replace a string containing $ sign

How can I replace a String $1 in Java? 如何在Java中替换String $1 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.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! 简单地将所有“$”替换为“REPLACED”!

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")); System.out.println(someHTMLCodeAsString.replaceAll(“\\\\ $ 1”,“REPLACED”));

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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