Freemarker:格式化字符串
Freemarker: Reformat String
我有一个 Freemarker 变量,它可以包含如下字符串:
myFirstStringExample
mySecondStringExample
myABCStringExample
myExample
我需要删除最后的 'Example',这将是任何可能的字符串。
我想以以下字符串结束:
My First String
My Second String
My ABC String
My
有没有简单的方法来做到这一点?
我设法想出这样的东西:
<#assign test="myFirstStringExample" />
<#assign first=test?matches("([a-z]+).*")?groups[1]?cap_first />
<#assign words=test?matches("([A-Z][a-z]*)") />
${first} <#list words as word><#if word?has_next>${word} </#if></#list>
它不仅适用于 myABCStringExample
与其说是 FreeMarker 问题,不如说是算法问题,但是你可以:
<#function camelCaseToCapWordsButLast(s)>
<#return s
<#-- "fooBar" to "foo bar": -->
?replace('([a-z])([A-Z])', ' ', 'r')
<#-- "FOOBar" to "FOO Bar": -->
?replace('([A-Z])([A-Z][a-z])', ' ', 'r')
<#-- and the easy part: -->
?cap_first?keep_before_last(' ')
>
</#function>
${camelCaseToCapWordsButLast('myFirstStringExample')}
${camelCaseToCapWordsButLast('mySecondStringExample')}
${camelCaseToCapWordsButLast('myABCStringExample')}
${camelCaseToCapWordsButLast('myExample')}
我有一个 Freemarker 变量,它可以包含如下字符串:
myFirstStringExample
mySecondStringExample
myABCStringExample
myExample
我需要删除最后的 'Example',这将是任何可能的字符串。 我想以以下字符串结束:
My First String
My Second String
My ABC String
My
有没有简单的方法来做到这一点?
我设法想出这样的东西:
<#assign test="myFirstStringExample" />
<#assign first=test?matches("([a-z]+).*")?groups[1]?cap_first />
<#assign words=test?matches("([A-Z][a-z]*)") />
${first} <#list words as word><#if word?has_next>${word} </#if></#list>
它不仅适用于 myABCStringExample
与其说是 FreeMarker 问题,不如说是算法问题,但是你可以:
<#function camelCaseToCapWordsButLast(s)>
<#return s
<#-- "fooBar" to "foo bar": -->
?replace('([a-z])([A-Z])', ' ', 'r')
<#-- "FOOBar" to "FOO Bar": -->
?replace('([A-Z])([A-Z][a-z])', ' ', 'r')
<#-- and the easy part: -->
?cap_first?keep_before_last(' ')
>
</#function>
${camelCaseToCapWordsButLast('myFirstStringExample')}
${camelCaseToCapWordsButLast('mySecondStringExample')}
${camelCaseToCapWordsButLast('myABCStringExample')}
${camelCaseToCapWordsButLast('myExample')}