很简单的字符串替换失败

时间:2012-03-16 15:32:07

标签: 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);

这导致

  

请在密码重置屏幕中输入以下代码:{CODE}(((((5RE2GT4FWH)))))如果您没有要求此代码,或者不知道这封电子邮件的内容是什么,你可以放心地忽略它。

这么简单的替换怎么能不起作用?我想也许问题是{CODE}的两个实例看起来很相似,但实际上是由不同的字符组成,但是我将其复制粘贴到另一个上面并且没有解决它。

5 个答案:

答案 0 :(得分:6)

要求知道:

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

由于缺少括号,首先在组合字符串的最后部分执行替换,然后才将这些部分连接在一起。

答案 1 :(得分:2)

您需要在完整字符串上调用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);

答案 2 :(得分:2)

您仅在最后replace()个对象上调用String:["If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it."]。

将[Stringreplace()之前的{{1}}存储到某个临时变量并重试,或者使用括号。

答案 3 :(得分:0)

您只是在 last 字符串字面值上调用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);

答案 4 :(得分:0)

这种解决方案可以将这种旧的Java代码样式升级为使用(旧的,但比这更新的)java.util.Formatter

的样式。
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);

然后会变成

Formatter formatter = new Formatter(new StringBuilder, Locale.US);
final String message = formatter.format("Please enter the following code in the password reset screen:\n\n %s ((((( %s )))))\n", codeStr);