我正在尝试替换以$
开头的部分字符串(我手动使用String中的参数)但由于某种原因它失败了。这就是我所拥有的:
public void sendNotificationOfAcceptedMeeting(String candidateName, DateTime dateTime) {
Map<String,String> params = new HashMap<String,String>();
params.put("date", dateTime.toString(DATETIME_FORMAT));
params.put("candidate", candidateName);
sendEmailWithTemplate(TEMPLATE_ALL_ACCEPTED, params);
}
然后:
private void sendEmailWithTemplate(String templateName, Map<String, String> params) {
EmailTemplate template = emailTemplateDao.getEmailTemplate(templateName);
String subject = applyTemplateParameters(template.getSubject(), params);
String body = applyTemplateParameters(template.getTetxBody(), params);
sendEmail(subject, body);
}
最后:
private String applyTemplateParameters(String templateText, Map<String, String> params) {
String toReturn = templateText;
if (params != null) {
System.out.println("map size: " + params.size());
for (Entry<String, String> entry : params.entrySet()) {
System.out.println("********************");
System.out.println(toReturn + " ***BEFORE");
toReturn.replace("$" + entry.getKey(), entry.getValue());
System.out.println("$" + entry.getKey() + " ***KEY");
System.out.println(entry.getValue() + " ***VALUE");
System.out.println(toReturn + " AFTER");
}
}
return toReturn;
}
正如您可能想到的那样,第二个方法使用我想要修改的String调用第三个方法,并映射参数及其值。第二种方法将template
String的路径设置为:
The meeting request at $date with $candidate was accepted by all interviewers.
然而,第三种方法中的sysouts打印:
map size: 2
********************
The meeting request at $date with $candidate was
accepted by all interviewers. ***BEFORE
$candidate ***KEY
Acceeedsasd Stetfghfghasd ***VALUE
The meeting request at $date with $candidate was
accepted by all interviewers. AFTER
********************
The meeting request at $date with $candidate was
accepted by all interviewers. ***BEFORE
$date ***KEY
27/12/2014 8:00 ***VALUE
The meeting request at $date with $candidate was
accepted by all interviewers. AFTER
这清楚地表明它不会替换参数...我想可能会$
打破它(正则表达式)但是replace()
,不像replaceAll()
需要字符串 - 而不是正则表达式。我没有想法,任何帮助表示赞赏。
答案 0 :(得分:3)
你必须这样做:
toReturn = toReturn.replace("$" + entry.getKey(), entry.getValue());
然后打印toReturn
的值答案 1 :(得分:1)
尝试更换&#34; $&#34;在您的代码中使用&#34; \ 0024&#34;
像这样:
toReturn = toReturn.replace(&#34; \ 0024&#34; + entry.getKey(),entry.getValue());
答案 2 :(得分:1)
问题是replace方法返回String
并且没有使用它。请参阅下文,我将结果放入replacedText
。
String replacedText = toReturn.replace("$" + entry.getKey(), entry.getValue());
System.out.println("$" + entry.getKey() + " ***KEY");
System.out.println(entry.getValue() + " ***VALUE");
System.out.println(replacedText+ " AFTER");
答案 3 :(得分:1)
字符串是不可变的,无法替换, 刚
toReturn = toReturn.replace("$...","")