您的位置:首页 > 其它

正则式获取特定标识的字符串并替换

2015-11-18 09:24 423 查看
正则式获取特定标识的字符串,

待处理字符串:#applyCom# 已经对单号为“#applyNo#”的“#applyType#”事项申请办结确认。请及时登录系统查看处理。

这里使用#*#的形式作为占位符,标识是需要待处理的地方。

使用正则式处理代码:

String content = "#applyCom# 已经对单号为“#applyNo#”的“#applyType#”事项申请办结确认。请及时登录系统查看处理。";

//组装需要替换的数据,用map里面的值替换掉占位符
HashMap<String , String> map = new HashMap<String, String>();
map.put("applyCom", "a");
map.put("applyType", "b");
map.put("applyNo", "c");

Pattern pat = Pattern.compile("(#[^#]*#)");//定义正则式

Matcher mat = pat.matcher(content);
int i = 0;
while (mat.find()) {//如果有匹配

String temp = mat.group(1).toString().substring(1, mat.group(1).toString().length()-1);//获得占位符,如:#applyCom# 就会获得applyCom

content = content.replace(mat.group(1), map.get(temp));//从map中获得值,并替换掉占位符

i++;
}
System.out.println(content);//打印最终字符串
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息