1. 程式人生 > >通過字串模板生成字串[附原始碼]

通過字串模板生成字串[附原始碼]

概述

java的String 類提供了format方法對字串進行格式化,但在實際使用中經常發現這個方法不夠靈活。所以在Lexer實現了一個。 其模板為一個字串,並對其中的 { 變量表達式 }內部的內容進行替換,其中用“\”作為轉義符;變量表達式類似於jsp中的el表示式。這個功能比較單一,直接用使用示例來展示。

使用示例

 	Map<String,Object> map = new HashMap<>(5);
    Map<String,Object> usreInfo = new HashMap<>(5);
    usreInfo.put(
"userCode","admin"); usreInfo.put("userName","管理員"); map.put("userInfo",usreInfo); String str = Pretreatment.mapTemplateString( "轉義符\\\\又一個轉義符\\{ {無法找到的變數} \"引號中的\\和{都不會被處理}\" "+ "你的姓名是{userInfo.userName}", map, "[沒有賦值]"); System.out.println(str );

資料結果

轉義符\又一個轉義符{ [
沒有賦值] "引號中的\\和{都不會被處理}" 你的姓名是管理員

需要說明的是:

  1. 因為java的字串也是用"“作為轉義符,所以在模板中要想輸出”“需要寫成”\\"。
  2. 模板中用單引號和雙引號引起來的字串都不錯分析,可以寫任意字串。
  3. Pretreatment.mapTemplateString 方法的第二個變數不僅僅可以式map可以式任意型別的變數。

原始碼

   /** mapTemplateString
     * 變數 形式如 {變數名} 注意這個和上面的不一,變數必須放在{}中
     *
     * @param template 模板,比如: 你的姓名是{usreCode} , 傳入有userCode建的map或者有userCode屬性的物件
     * @param object 傳入的物件,可以是一個Map 、JSON 或者Pojo
     * @param nullValue 找不到變數時的值
     * @return 新的表示式
     */
public static String mapTemplateString(String template,Object object, String nullValue){ if(StringUtils.isBlank(template)){ return nullValue; } Lexer varTemplate = new Lexer(); varTemplate.setFormula(template); StringBuilder mapString = new StringBuilder(); int nlen = template.length(); int bp = 0; while(true) { String aword = varTemplate.getAWord(); while(true){ // 檢查轉義符 if("\\".equals(aword)){ int ep = varTemplate.getCurrPos(); mapString.append(template.substring(bp, ep - 1)); //獲取 \\ 後面的一個字元 mapString.append(template.charAt(ep)); varTemplate.setPosition(ep+1); bp = varTemplate.getCurrPos(); //aword = varTemplate.getAWord(); }else if("{".equals(aword) || aword==null || "".equals(aword)){ break; } aword = varTemplate.getAWord(); } if(!"{".equals(aword)) break; int ep = varTemplate.getCurrPos(); if(ep-1>bp){ mapString.append(template.substring(bp, ep - 1)); } varTemplate.seekToRightBrace(); bp = varTemplate.getCurrPos(); if(bp-1>ep) { String valueName = template.substring(ep, bp - 1); mapString.append(GeneralAlgorithm.nvl( StringBaseOpt.objectToString( ReflectionOpt.attainExpressionValue(object,valueName)),nullValue)); } } if(bp<nlen) mapString.append(template.substring(bp)); return mapString.toString(); }