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

Freemarker中remove_ending与keep_before内置函数的区别探讨

Freemarker中remove_ending与keep_before的区别

这两个字符串内置函数的核心逻辑和适用场景有明显差异,具体如下:

1. 核心处理逻辑不同

  • remove_ending(suffix):只盯着字符串末尾,如果刚好以指定后缀结尾,就把这个后缀砍掉;要是不匹配,原封不动返回原字符串。
  • keep_before(substring):在字符串里找指定子串第一次出现的位置,然后截取这个位置之前的所有内容;如果子串不存在,同样返回原字符串。

2. 匹配规则有区别

  • remove_ending是严格的后缀匹配,只有后缀完全吻合才会生效。
  • keep_before是任意位置的首次匹配,不管子串在开头、中间还是结尾,只要出现就会截断。

3. 实际效果对比示例

用几个例子能更直观看出差异:

  • 场景1:字符串为"report.pdf"
    • "report.pdf"?remove_ending(".pdf") → "report"(匹配后缀,移除成功)
    • "report.pdf"?keep_before(".pdf") → "report"(结果相同,但逻辑是找到.pdf后截取前面部分)
  • 场景2:字符串为"document.pdf.zip"
    • "document.pdf.zip"?remove_ending(".pdf") → "document.pdf.zip"(后缀是.zip,不匹配.pdf,返回原串)
    • "document.pdf.zip"?keep_before(".pdf") → "document"(找到首次出现的.pdf,截取前面内容)
  • 场景3:字符串为"helloworld"
    • "helloworld"?remove_ending("world") → "hello"(匹配末尾后缀)
    • "helloworld"?keep_before("world") → "hello"(结果一致)
  • 场景4:字符串为"worldhello"
    • "worldhello"?remove_ending("world") → "worldhello"(后缀不是world,返回原串)
    • "worldhello"?keep_before("world") → ""(开头就匹配到world,截取前面的空串)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:45:46