Freemaker Replace函数的正则表达式运用
replace(param1,param2,param3)
param1 正则表达式;param2 将匹配的字符替换成指定字符;param3 模式
param3 参数如下
模式 | i | r | m | s | c | f |
replace | 支持 | 支持 | 只和r 组合 | 只和r 组合 | 只和r 组合 | 支持 |
模式解释:
i: case insensitive: 忽略大小写
f: first only. that is, replace/find/etc. only the first occurrence of something.
r: the substring to find is a regular expression.标准正则表达式(http://docs.oracle.com/javase/7/docs/api/java/util/regex/pattern.html )
m: multi-line mode for regular expressions. in multi-line mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the string. by default these expressions only match at the beginning and the end of the entire string. note that ^ and $ doesn't match the line-break character itself.
s: enables dot-all mode for regular expressions (same as perl singe-line mode). in dot-all mode, the expression . matches any character, including a line terminator. by default this expression does not match line terminators.
c: permits whitespace and comments in regular expressions.在正则表达式中允许空格和注释。
范例如下:
<#assign s = 'foo bar baar'> ${s?replace('ba', 'xy')} i: ${s?replace('ba', 'xy', 'i')} if: ${s?replace('ba', 'xy', 'if')} r: ${s?replace('ba*', 'xy', 'r')} ri: ${s?replace('ba*', 'xy', 'ri')} rif: ${s?replace('ba*', 'xy', 'rif')}
输出结果:
foo bar xyar
i: foo xyr xyar
if: foo xyr baar
r: foo xyar xyr
ri: foo xyr xyr
rif: foo xyr baar
更多范例:
原文:str = 2积分兑换30元优惠券
${str?replace('\\b\\d+积分','','r')}
输出:兑换30元优惠券
ps:freemarker的replace功能
替换字符串 replace
${s?replace(‘ba', ‘xy' )} ${s?replace(‘ba', ‘xy' , ‘规则参数')}
将s里的所有的ba替换成xy 规则参数包含: i r m s c f 具体含义如下:
· i: 大小写不区分.
· f: 只替换第一个出现被替换字符串的字符串
· r: xy是正则表达式
· m: multi-line mode for regular expressions. in multi-line mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the string. by default these expressions only match at the beginning and the end of the entire string.
· s: enables dotall mode for regular expressions (same as perl singe-line mode). in dotall mode, the expression . matches any character, including a line terminator. by default this expression does not match line terminators.
· c: permits whitespace and comments in regular expressions.
上一篇: java统计字符串中指定元素出现次数方法
下一篇: 深入研究kafka原理