?right_pad在?replace捕获组中未正确计算长度的问题咨询
Freemarker正则替换捕获组用right_pad失效的替代方案及Bug反馈
替代实现方法
别在正则替换的捕获组里直接用?right_pad,换个分步处理的思路就能解决列对齐问题:
- 提取所有单元格内容:用
<#list>配合字符串拆分,把HTML表格里的每行、每个单元格的纯文本内容提取出来,存成二维列表(比如tableRows,每个元素对应一行的单元格内容数组)。 - 计算每列最大长度:遍历这个二维列表,统计每一列里最长的单元格内容长度,存在
columnMaxLengths数组里。 - 生成对齐的纯文本:再次遍历每行,对每个单元格用
?right_pad(columnMaxLengths[列索引])补空格,最后拼接成对齐的文本行。
示例代码片段:
<#-- 假设htmlTable是原始HTML表格字符串 --> <#assign tableRows = []> <#-- 提取每行的单元格内容 --> <#list htmlTable?split('<tr>') as row> <#if row?contains('</tr>')> <#assign cells = []> <#list row?split('<td>') as cell> <#if cell?contains('</td>')> <#assign cellContent = cell?substring(0, cell?indexOf('</td>'))?trim> <#assign cells = cells + [cellContent]> </#if> </#list> <#if cells?size > 0> <#assign tableRows = tableRows + [cells]> </#if> </#if> </#list> <#-- 计算每列的最大长度 --> <#assign columnMaxLengths = []> <#if tableRows?size > 0> <#list tableRows[0] as _> <#assign columnMaxLengths = columnMaxLengths + [0]> </#list> <#list tableRows as row> <#list row as idx, cell> <#if cell?length > columnMaxLengths[idx]> <#assign columnMaxLengths[idx] = cell?length> </#if> </#list> </#list> </#if> <#-- 生成对齐的纯文本表格 --> <#list tableRows as row> <#assign line = ''> <#list row as idx, cell> <#assign paddedCell = cell?right_pad(columnMaxLengths[idx])> <#assign line = line + paddedCell + ' '> <!-- 单元格之间加分隔空格 --> </#list> ${line?trim} </#list>
Bug登记相关
如果要提交这个Bug:
- 先注册Jira账号,进入Freemarker项目空间创建新Issue,描述里要包含:使用的Freemarker版本、触发问题的正则替换+
?right_pad代码片段、预期的对齐效果和实际偏移的对比。 - 也可以在Freemarker的官方社区(邮件列表、GitHub讨论区)发帖说明问题细节,请求维护者协助登记,或者邀请你进入项目Jira自行提交。
内容的提问来源于stack exchange,提问作者bdasliva83
相关产品推荐
相关产品推荐

