前言
相信大家可能曾遇到过这种情况,在开发中类似站内信的需求时,我们经常要使用字符串模板,比如
?
|
1
|
尊敬的用户${name}。。。。
|
里面的${name}就可以替换为用户的用户名。
下面使用正则表达式简单实现一下这个功能:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/**
* 根据键值对填充字符串,如("hello ${name}",{name:"xiaoming"})
* 输出:
* @param content
* @param map
* @return
*/
public static String renderString(String content, Map<String, String> map){
Set<Entry<String, String>> sets = map.entrySet();
for(Entry<String, String> entry : sets) {
String regex = "\\\\$\\\\{" + entry.getKey() + "\\\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
content = matcher.replaceAll(entry.getValue());
}
return content;
}
|
在map里存储了键值对,然后获取键值对的集合,遍历集合进行对字符串的渲染
实例测试:
?
|
1
2
3
4
5
6
7
8
9
|
@Test
public void renderString() {
String content = "hello ${name}, 1 2 3 4 5 ${six} 7, again ${name}. ";
Map<String, String> map = new HashMap<>();
map.put("name", "java");
map.put("six", "6");
content = StringHelper.renderString(content, map);
System.out.println(content);
}
|
有两个变量需要替换,name和six,对应的值分别为Java和6,同时name调用了两次。
结果:
?
|
1
|
hello java, 1 2 3 4 5 6 7, again java.
|
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 84
-
2025-05-27 99
-
2025-05-27 24
-
2025-05-29 98
-
2025-05-25 82
热门评论

