String level = "INFO";
String stamp = "2013-04-26";
String message = "Log me, please!";
String template = "[%LVL%] - %STAMP%\n%MSG%";
String log = template.replaceAll("%LVL%", level);
log = template.replaceAll("%STAMP%", stamp);
log = template.replaceAll("%MSG%", message);
System.out.println(log);
这打印:
[%LVL%] - %STAMP%
Log me, please!
为什么第 3 个 replaceAll("%MSG%", message);
起作用,而前 2 个不起作用?
最佳答案
它不起作用,因为您没有在其他语句中使用替换变量。您始终使用 template
,因此您将始终替换原始模板变量,而不是(增量)替换的模板变量。所以最后,您只需将原始 模板
替换为 %MSG%
模式即可。
它应该是:
String log = template.replaceAll("%LVL%", level);
log = log.replaceAll("%STAMP%", stamp);
log = log.replaceAll("%MSG%", message);
编辑
正如@Fildor 所建议的,String.format()
将是一个更好的解决方案:
String.format("%s - %s\n%s", level, stamp, message);
关于java - 为什么这些 Java replaceAll 语句不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16232641/