java - 使用 Velocity Template 将索引替换为值

标签 java replace velocity

我是 java Velocity Templates 的新手。我有一个字符串,其中有一些数字占位符/变量。我需要将它们替换为相应的值。我怎样才能在java中实现这一点?

代码示例:

String templateString = "Replacing $0 with its value.";
VelocityContext context = new VelocityContext();
context.put("0", "Sample value");

StringWriter output = new StringWriter();
Velocity.evaluate(context, output, "log or null", templateString);

System.out.println("output: " + output);

上面的代码没有用“示例值”替换 $0 变量,但当我使用字符串而不是 $0 作为占位符/变量时,它就可以工作。是否有任何解决方法可以用 $0 的值替换它?感谢您对此的帮助。

谢谢。

最佳答案

Velocity 本身没有解决方法:解析器不允许引用名称以数字开头。

因此,您必须预处理模板,例如:

templateString = templateString.replaceAll("\\$(\\d+)","\\$_$1");
context.put("_0", "Sample value");
...

关于java - 使用 Velocity Template 将索引替换为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41793932/

相关文章:

java - 在没有 JRuby 和 Java 的情况下从 Ruby 访问 JMX

java - UFT-启动Java应用程序

javascript - 替换 HTML 元素中的字符

c# - 在 C# 中使用正则表达式突出显示 html 中的单词

java - 取消设置 Velocity 中的变量

java - libgdx 列表小部件的两个问题

java - 如何从网络发送数据到linux服务器

python - 使用Python的正则表达式在某些字符之间插入符号

java - 找不到类路径的速度模板

java - 将对象作为 "root"放入 VelocityContext