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

前端之家收集整理的这篇文章主要介绍了正则式获取特定标识的字符串并替换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

正则式获取特定标识的字符串,

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

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

使用正则式处理代码

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

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


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

Matchermat=pat.matcher(content);
inti=0;
while(mat.find()){//如果有匹配

Stringtemp=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);//打印最终字符串
原文链接:https://www.f2er.com/regex/359779.html

猜你在找的正则表达式相关文章