java正则表达式取的${}中的数据,或者替换

取值

   public String formatParamCode(String paramCode){
    return paramCode.replaceAll("\\$", "").replaceAll("\\{", "").replaceAll("\\}", "");
   }

   public String composeMessage(String data, Map<String,String> paramData) throws Exception {
    String regex = "\\$\\{(.+?)\\}";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(data);
    StringBuffer msg = new StringBuffer();
    while (matcher.find()) {
      String key = matcher.group(1);// 键名
      String value = (String) paramData.get(key);// 键值
      if(value == null) {
        value = "";
      } else {
        value = value.replaceAll("\\$", "\\\\\\$");
      }
      matcher.appendReplacement(msg, value);
    }
    matcher.appendTail(msg);
    return msg.toString();
    }


    //取${} 变量,并存到Map中
    Map<String,String> paramData = new HashMap<String,String>();
    Pattern pattern = Pattern.compile("(\\$\\{[^\\}]+})"); 
    Matcher matcher = pattern.matcher(data);  
    while(matcher.find()){
      String paramCode = matcher.group(1);
      paramData.put(formatParamCode(paramCode),queryParamValue(paramCode));
    }
    //替换值
    try {  
        return composeMessage(data, paramData);
    } catch (Exception e) {  
        e.printStackTrace();  
    }  

你可能感兴趣的:(java正则表达式)