java - 非常简单的字符串替换失败

标签 java replace

final String message =
                        "Please enter the following code in the password reset screen:\n" +
                                "\n"+
                                "{CODE} (((((" + codeStr + ")))))\n" +
                                "If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it."
                                .replace("{CODE}", codeStr);

这会导致

Please enter the following code in the password reset screen: {CODE} (((((5RE2GT4FWH))))) If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it.

这么简单的替换怎么会不起作用呢?我认为问题可能在于 {CODE} 的两个实例看起来很相似,但实际上由不同的字符组成,但我将一个复制粘贴到另一个上,但没有解决问题。

最佳答案

问即知:

final String message =
                    (
                            "Please enter the following code in the password reset screen:\n" +
                            "\n"+
                            "{CODE}" + codeStr + "\n" +
                            "If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it."
                    )
                    .replace("{CODE}", codeStr);

由于缺少括号,所以先对组成字符串的最后部分进行替换,然后才将各部分连接在一起。

关于java - 非常简单的字符串替换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9740129/

相关文章:

java - 使用 log4j 写入日志文件

java - 如何放心认证?

java - 如何获取Excel中选定字符串的行、列坐标

java - 在 Jackson 序列化和反序列化时保留类型信息

mysql - 如何在我不知道其长度的子字符串中间使用通配符?

java - 如何用java中的相应字符替换特定字符?

java - JAXB XJC 绑定(bind) : renaming @XmlRootElement and @XmlType together

javascript - 关于 javascript 的问题 - string.replace()

perl - 在 shell 命令行中将两个换行符替换为一个

将 'qualify' 列值 'yes' 和 'no' 替换为 True 和 False 的 Python 程序