美文网首页
利用正则替换{key}

利用正则替换{key}

作者: 8813d76fee36 | 来源:发表于2017-12-12 18:03 被阅读7次
    • 需求:
      使用对应值替换/home/test/{prvId}/{issueNo}/{gameId}/模版中的{key},key的顺序变化时也能正确替换。
    public class StringFormatUtil {
    
        //匹配{key}的正则
        private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
        private static Matcher matcher;
    
        /**
         * 替换{key}占位符
         * @param sourStr 需要替换的模版
         * @param param 参数map,map的key与模版中的key对应
         * @return
         */
        public static String stringFormat(String sourStr, Map<String, Object> param) {
    
            String targetStr = sourStr;
            if (param == null) {
                return targetStr;
            }
    
            matcher = PATTERN.matcher(targetStr);
    
            while (matcher.find()) {
                //
                String key = matcher.group();
                //去掉{},保留其中的key值
                String keyClone = key.substring(1, key.length() - 1).trim();
                Object value = param.get(keyClone);
    
                //替换
                if (value != null) {
                    targetStr = targetStr.replace(key, value.toString());
                }
            }
    
            return targetStr;
        }
    
        /**
         * 替换{key}占位符
         * @param sourStr 需要替换的模版
         * @param paramObj 参数对象,字段名与{key}对应
         * @return
         */
        public static String stringFormat(String sourStr, Object paramObj) {
    
            String targetStr = sourStr;
            if (paramObj == null) {
                return targetStr;
            }
    
            PropertyDescriptor pd;
            Method method;
    
            while (matcher.find()) {
                String key = matcher.group();
                String keyClone = key.substring(1, key.length() - 1).trim();
                try {
                    pd = new PropertyDescriptor(keyClone, paramObj.getClass());
                    method = pd.getReadMethod();
                    Object value = method.invoke(paramObj);
                    if (value != null) {
                        targetStr = targetStr.replace(sourStr, value.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            return targetStr;
        }
    }
    
    • 测试
    public static void main(String[] args) {
    
            String path = "/home/test/{prvId}/{issueNo}/{gameId}/";
            Map<String, Object> params = new HashMap<>();
            params.put("gameId", "gameid");
            params.put("issueNo", "issueno");
            params.put("prvId", "prvid");
    
            String result = StringFormatUtil.stringFormat(path, params);
            System.out.println(result);
        }
    
    • 效果
    /home/test/prvid/issueno/gameid/
    

    相关文章

      网友评论

          本文标题:利用正则替换{key}

          本文链接:https://www.haomeiwen.com/subject/eqvnixtx.html