java 字符串模板匹配_字符串模板匹配 - 采女孩的小蘑菇1的个人空间 - OSCHINA - 中文开源技术交流社区...

package com.adam;

import java.util.HashMap;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class StringTemplateParser {

private String pstartTag = "${";

private String pendTag = "}";

/**

*

* @param template 要解析的字符串

* @param map 对应的值

* @return 返回解析结果

*/

public String parse(String template,Map map){

StringBuffer temp = new StringBuffer(template);

Map tagMap = this.getTagIndex(template);

for(Map.Entry entry:tagMap.entrySet()){

//获得标识符

String tag = entry.getValue();

//获得替换的值,如果没有,则不变

String repVal = map.get(entry.getKey())==null?entry.getValue():map.get(entry.getKey());

//获得标识符在字符串中出现的次数

int index = 0;

//判断同一个标识符在字符串中出现的次数

while((index=template.indexOf(tag,index))!=-1){

//替换

//System.out.println(tag+"位置:"+index);

temp = temp.replace(temp.indexOf(tag), temp.indexOf(tag)+tag.length(), repVal);

index += tag.length();

}

}

return temp.toString();

}

/**

* 获得key和对应的标识符如{age=${age}, name=${name}}

* @param template

* @return

*/

protected Map getTagIndex(String template){

Map map = new HashMap();

Pattern pattern = Pattern.compile("\\$\\{[\\w]+\\}") ;

Matcher matcher = pattern.matcher(template);

int pstartLen = pstartTag.length();

while(matcher.find()){

//获得标示符

String tag = matcher.group();

//获得key

String key = tag.substring(pstartLen, tag.lastIndexOf(pendTag));

map.put(key, tag);

}

return map;

}

public static void main(String[] args) {

String template = "${age} hi,${name},${name} are you ${age}?";

Map map = new HashMap();

map.put("name", "adam");

map.put("age", "25");

StringTemplateParser stp = new StringTemplateParser();

System.out.println(stp.parse(template,map));

System.out.println(stp.getTagIndex(template));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值