一串字符中有多个{},需要把{}中的内容找出验证内容是否正确,前端和后端都要验证,所以要分别用js 和Java对字串进行处理。
字串:“用户您好,你参加的${activityName}活动已经结束,确定您已经完成活动任务目标,您的奖励如下:${awardList}”
1、js正则匹配字符串中多个{}中的内容
var wildcards = content.match(/(\${.*?\})/g) if (wildcards == null) { L.msg.error("模板通配符不正确"); return globalReturnFlag; } else { if (wildcards[0] != "${activityName}") { L.msg.error("模板通配符不正确"); } else if (wildcards[1] != "${awardList}") { L.msg.error("模板通配符不正确"); } }
2、Java正则匹配,java中和js方式不太一样,他没有/g匹配多个的方式,需要用find(),循环查找
Pattern p = Pattern.compile("(\\$\\{.*?\\})"); Matcher m = p.matcher(bean.getContent()); int matcherTimes = 0; while(m.find()) { String str = m.group(0); if(!msgTemplateWildcard.contains(str)){ throw new ChinasoException(AlertMessage.getMessageObjByKey("msgMsgTemplateContentWildcardNotExist")); } }