1、包含{{ cart.total_price }},不包含 minus:
Pattern.compile("(\\{\\{\\s*cart.total_price\\s*\\|*(?!.*minus:)[^\\}\\}]*\\}\\})");
校验:
{{ cart.total_price}} 通过
{{ cart.total_price | money_without_trailing_zeros }} 通过
{{ cart.total_price | minus: threshold_in_cents | abs | money_without_trailing_zeros }} 不通过
2、正则表达式匹配 {key} ,并且替换 key 内容
public static final String CONTAINS = "(?<=\\{)(.*?)(?=\\})";
/**
* 解析消息模板
*
* @param template 模板字符串
* @param datas 模板填充数据
* @return 解析结果
*/
public static String parseMessage(String template, Map<String, Object> datas) {
Pattern pattern = Pattern.compile(CONTAINS);
Matcher matcher = pattern.matcher(template);
StringBuffer parseContent = new StringBuffer();
String key = "";
int start = 0;
while (matcher.find()) {
key = matcher.group().trim();
parseContent.append(template.substring(start, matcher.start() - 1));
parseContent.append(datas.get(key));
start = matcher.end() + 1;
}
if (parseContent.equals("")) {
parseContent.append(template);
} else {
parseContent.append(template.substring(start));
}
return parseContent.toString();
}
public static void main(String[] args) {
String template = "亲爱的主人,{enterprise}企业发布了{task}任务,为了毛栗,冲鸭!";
Map<String, Object> datas = new HashMap<>();
datas.put("enterprise", "龙珠");
datas.put("task", "天下第一武道会");
String result = parseMessage(template, datas);
System.out.println(result);
}
3、从字符串中抽取数字
private static final Pattern pattern_number = Pattern.compile("\\d+");
/**
* 抽取数字
*
* @param text 内容
* @return 数字
*/
public List<BigDecimal> extractNumber(String text) {
Matcher matcher = pattern_number.matcher(text);
List<BigDecimal> numberList = new ArrayList<>();
while (matcher.find()) {
numberList.add(new BigDecimal(matcher.group()));
}
if (CollectionUtil.isNotEmpty(numberList)) {
return numberList;
}
return Collections.emptyList();
}
使用说明
?<= 表示后面的内容是否等于
?<= 表示以后面的内容开头
?! 表示后面的内容是否不是这个
?<!= 表示后面的内容是否不以这个开头