步骤一,先用正则表达式找出要替换的组数据,可以得到分组数据的start,end索引
步骤二,用stringbuilder的有索引参数的replace方法替换
public String replaceProperty(String plan,String subject,String condition) throws Exception {
String regex = "\\{(\\D+?)}";
Pattern pattern = Pattern.compile(regex);
StringBuilder sbc = new StringBuilder();
Matcher match;
for (match = pattern.matcher(condition); match.find(); match = pattern.matcher(condition)){
String id = LoyaltyConfig.findIdByProperty(plan,subject,match.group(1));
sbc = new StringBuilder(condition).replace(match.start(1),match.end(1),id);
condition = sbc.toString();
}
return sbc.toString();
}
public String replaceProperty(String plan,String subject,String condition) throws Exception { String regex = "\\{(.+?)}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(condition); StringBuffer sbc = new StringBuffer(); while (matcher.find()){ String id = LoyaltyConfig.findIdByProperty(plan,subject,matcher.group(1)); matcher.appendReplacement(sbc,"{" + id + "}"); } matcher.appendTail(sbc); return sbc.toString(); }