我在用 java 替换字符串时遇到问题...
行是:
subject = subject.replaceAll("\\[calEvent\\]", calSubject);
此行不适用于 calSubject 中的 $ 符号。
主题变量是什么,来自文件的动态主题行变量。例如像这样: Calnot = [calEvent]
我想做的是用主题变量替换 calEvent 占位符。但是我的做法不起作用,因为当主题包含 $ 符号时它会崩溃。
知道我该如何做到这一点,这样即使主题包含 $ 符号或与此相关的任何字符,它也不会中断吗?
最佳答案
那是因为美元符号是替换字符串中的特殊字符,使用Matcher.quoteReplacement()
来转义这种字符。
subject = subject.replaceAll("\\[calEvent\\]", Matcher.quoteReplacement(calSubject));
来自 String.replaceAll()
的文档:
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. UseMatcher.quoteReplacement(java.lang.String)
to suppress the special meaning of these characters, if desired.
请注意,美元符号用于引用正则表达式中相应的捕获组($0
、$1
等)。
编辑
Matcher.quoteReplacement()
已在 Java 1.5 中引入,如果您卡在 Java 1.4 中,则必须通过将其替换为 手动转义
在字符串中。但是由于 $
\$String.replaceAll()
也会将 \
和 $
作为特殊字符,你必须将它们转义一次,而且你还必须为 Java 运行时再次转义所有 \
。
("$", "\$") /* what we want */
("\$", "\\\$") /* RegExp engine escape */
("\\$", "\\\\\\$") /* Java runtime escape */
所以我们得到:
calSubject = calSubject.replaceAll("\\$", "\\\\\\$");
关于java - 字符串替换用 $ 符号抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16018831/