You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Velocity 1.7解析含连字符的字符串时抛出语法解析异常

Velocity 1.7 语法解析异常解决办法

问题场景

处理字符串 #TestString (test-string this is random string) 时,Velocity引擎抛出解析异常:

org.apache.velocity.exception.ParseErrorException: Encountered "-" at PERSONALISATION[line 1, column 18]
Was expecting one of:
...
...
...

使用环境:Velocity 1.7,上下文仅注入Escape Tool,核心代码如下:

VelocityContext velocityContext = new VelocityContext();
velocityContext.put("esc", new EscapeTool());
StringWriter writer = new StringWriter();
getVelocityEngine().evaluate(velocityContext, writer, "TEST-TEMPLATE", text); 

问题原因

Velocity 1.7的语法解析规则中,#开头的指令括号内的参数若包含连字符-,会被判定为语法错误。解析器在test-string的-位置,预期的是右括号或空格,而非连字符,因此触发异常。

解决方案

根据实际需求选择对应方案:

  • 若#TestString是自定义指令:将带连字符的参数用引号包裹,标记为字符串字面量,修改后的字符串为:
    #TestString ("test-string" this is random string)
    这样Velocity会正确识别"test-string"为字符串参数,而非标识符。
  • 若只是想输出这段文本(#并非指令标记):转义#符号,有两种方式:
    1. 使用上下文里的EscapeTool:${esc.hash}TestString (test-string this is random string)
    2. 使用Velocity原生转义符:\#TestString (test-string this is random string)(默认转义开关已开启)

内容的提问来源于stack exchange,提问作者Harshil Panwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 00:19:57