java 字符串占位符替换之字符串占位符实现(java简单模板渲染实现)

  • 简单实现

关于java字符串占位符替换,专业方式是使用String.format和MessageFormat.format功能,这里提供个简单的基于正则实现的字符串占位符实现

    public static String tpl(String tplStr,Map<String, Object> data ) {
         Matcher m=Pattern.compile("\\{([\\w\\.]*)\\}").matcher(tplStr);
            while(m.find()){
                   String group=m.group();
                   group= group.replaceAll("\\{|\\}", "");
                   String value="";
                   if(null!=data.get(group)){
                       value=String.valueOf(data.get(group));
                   }
                   tplStr=tplStr.replace(m.group(),value);
            }
            return tplStr;
    }
  • 使用freemarker等模板引擎
private String defaultCharacter = "UTF-8";
private Configuration cfg;
public FreemarkerUtils() {
        cfg = new Configuration();
        cfg.setDefaultEncoding(defaultCharacter);
      cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX); 
    }
public  String generateString(
               Map data,  String tplStr) {
          String result = null;
          String name="myStrTpl";
          try { 
              StringTemplateLoader stringTemplateLoader= new StringTemplateLoader();
              stringTemplateLoader.putTemplate(name, tplStr);
                cfg.setTemplateLoader(stringTemplateLoader); 
               Template template = cfg.getTemplate(name,defaultCharacter);
                StringWriter out = new StringWriter(); 
                template.process(data, out);  
                out.flush();  
                result= out.toString();
                out.close(); 
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
          return result;
      }

你可能感兴趣的:(java组件)