java筛选出字符串中所有符合规则的子字符串
-
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class test { private static final String[] array = {"MAX","MIN"}; private String formulaCalculator(String formula){ for (int i = 0; i < array.length; i++){ if (formula.contains(array[i])){ formula = formula.replace(array[i],"this.$"+array[i]); } } Pattern compile = Pattern.compile("(\\#\\{.*?\\})"); Matcher matcher = compile.matcher(formula); int matcher_start = 0; List<String> list = new ArrayList<>(); while(matcher.find(matcher_start)){ list.add(matcher.group(1)); matcher_start = matcher.end(); } HashMap<String, String> hashMap = new HashMap<>(); list.stream().distinct().forEach(item ->{ String bitBefore = StringUtils.substringAfter(StringUtils.substringBrfore(item,"."),"{"); String bitAfter = StringUtils.substringBrfore(StringUtils.substringAfter(item,"."),"}"); hashMap.put(item,"this."+bitBefore+"_value."+bitAfter); }); for (Map.Entry<String,String> entry : hashMap.entrySet()){ formula = formula.replace(entry.getKey(),entry.getValue()); } return formula; }}