java 替换字符串模板(模板渲染)
java渲染字符串模板,也就是说在java字符串模板中设置变量字符串,使用变量去渲染指定模板中设置好的变量字符串。下面介绍4种替换模板方式:
1、使用内置String.format
String message = String.format("您好%s,晚上好!您目前余额:%.2f元,积分:%d", "张三", 10.155, 10);
System.out.println(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
2、使用内置MessageFormat
String message = MessageFormat.format("您好{0},晚上好!您目前余额:{1,number,#.##}元,积分:{2}", "张三", 10.155, 10);
System.out.println(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
3、使用自定义封装
。。。。。
private static Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
。。。。。
public static String processTemplate(String template, Map<String, Object> params){
StringBuffer sb = new StringBuffer();
while (m.find()) {
String param = m.group();
Object value = params.get(param.substring(2, param.length() - 1));
m.appendReplacement(sb, value==null ? "" : value.toString());
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args){
Map map = new HashMap();
map.put("name", "张三");
map.put("money", String.format("%.2f", 10.155));
map.put("point", 10);
message = processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map);
System.out.println(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
}
4、使用模板引擎freemarker
首先引入freemarker.jar,这里以2.3.23版本为例,如果使用maven的配置pom.xml
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
try {
map = new HashMap();
map.put("name", "张三");
map.put("money", 10.155);
map.put("point", 10);
Template template = new Template("strTpl", "您好${name},晚上好!您目前余额:${money?string(\"#.##\")}元,积分:${point}", new Configuration(new Version("2.3.23")));
StringWriter result = new StringWriter();
template.process(map, result);
System.out.println(result.toString());
//您好张三,晚上好!您目前余额:10.16元,积分:10
}catch(Exception e){
e.printStackTrace();
}
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version; import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* Created by cxq on 2018-01-07.
*/
public class Tpl { public static Configuration cfg; static {
cfg = new Configuration(new Version("2.3.23"));
} public static void main(String[] args) {
Object[] obj = new Object[]{"张三", String.format("%.2f", 10.155), 10};
System.out.println(processFormat("您好%s,晚上好!您目前余额:%s元,积分:%d", obj));
System.out.println(processMessage("您好{0},晚上好!您目前余额:{1}元,积分:{2}", obj)); Map map = new HashMap();
map.put("name", "张三");
map.put("money", String.format("%.2f", 10.155));
map.put("point", 10);
System.out.println(processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
System.out.println(processFreemarker("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
} /**
* String.format渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processFormat(String template, Object... params) {
if (template == null || params == null)
return null;
return String.format(template, params);
} /**
* MessageFormat渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processMessage(String template, Object... params) {
if (template == null || params == null)
return null;
return MessageFormat.format(template, params);
} /**
* 自定义渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processTemplate(String template, Map<String, Object> params) {
if (template == null || params == null)
return null;
StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
while (m.find()) {
String param = m.group();
Object value = params.get(param.substring(2, param.length() - 1));
m.appendReplacement(sb, value == null ? "" : value.toString());
}
m.appendTail(sb);
return sb.toString();
} /**
* Freemarker渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processFreemarker(String template, Map<String, Object> params) {
if (template == null || params == null)
return null;
try {
StringWriter result = new StringWriter();
Template tpl = new Template("strTpl", template, cfg);
tpl.process(params, result);
return result.toString();
} catch (Exception e) {
return null;
}
} }
综合,完整示例:
http://www.weizhixi.com/user/index/article/id/53.html
/**
* 简单实现${}模板功能
* 如${aa} cc ${bb} 其中 ${aa}, ${bb} 为占位符. 可用相关变量进行替换
* @param templateStr 模板字符串
* @param data 替换的变量值
* @param defaultNullReplaceVals 默认null值替换字符, 如果不提供, 则为字符串""
* @return 返回替换后的字符串, 如果模板字符串为null, 则返回null
*/ @SuppressWarnings("unchecked")
public static String simpleTemplate(String templateStr, Map<String, ?> data, String... defaultNullReplaceVals) {
if(templateStr == null) return null; if(data == null) data = Collections.EMPTY_MAP; String nullReplaceVal = defaultNullReplaceVals.length > 0 ? defaultNullReplaceVals[0] : "";
Pattern pattern = Pattern.compile("\\$\\{([^}]+)}"); StringBuffer newValue = new StringBuffer(templateStr.length()); Matcher matcher = pattern.matcher(templateStr); while (matcher.find()) {
String key = matcher.group(1);
String r = data.get(key) != null ? data.get(key).toString() : nullReplaceVal;
matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\")); //这个是为了替换windows下的文件目录在java里用\\表示
} matcher.appendTail(newValue); return newValue.toString();
} //测试方法
public static void main(String[] args) {
String tmpLine = "简历:\n 姓名: ${姓} ${名} \n 性别: ${性别}\n 年龄: ${年龄} \n";
Map<String, Object> data = new HashMap<String, Object>();
data.put("姓", "wen");
data.put("名", "66");
data.put("性别", "man");
data.put("年龄", "222"); System.out.println(simpleTemplate(tmpLine, null, "--"));
}
http://wen66.iteye.com/blog/830526
static final String jsonStr = "{\"name\":\"11\",\"time\":\"2014-10-21\"}";
static final String template = "亲爱的用户${name},你好,上次登录时间为${time}";
static String generateWelcome(String jsonStr,String template){
Gson gson = new Gson();
HashMap jsonMap = gson.fromJson(jsonStr, HashMap.class);
for (Object s : jsonMap.keySet()) {
template = template.replaceAll("\\$\\{".concat(s.toString()).concat("\\}")
, jsonMap.get(s.toString()).toString());
}
return template;
}
public static void main(String[] args) throws IOException {
System.out.println(generateWelcome(jsonStr,template));
}
https://segmentfault.com/q/1010000002484866
在开发中类似站内信的需求时,我们经常要使用字符串模板,比如
尊敬的用户${name}。。。。
里面的${name}就可以替换为用户的用户名。
下面使用正则表达式简单实现一下这个功能:
/**
* 根据键值对填充字符串,如("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里存储了键值对,然后获取键值对的集合,遍历集合进行对字符串的渲染
测试:
@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调用了两次。
结果:
hello java, 1 2 3 4 5 6 7, again java.
http://www.zgljl2012.com/javazheng-ze-biao-da-shi-shi-xian-name-xing-shi-de-zi-fu-chuan-mo-ban/
java 替换字符串模板(模板渲染)的更多相关文章
- java替换字符串和用indexof查找字符
java自带替换 String s="hlz_and_hourui哈哈"; String new_S=s.replaceAll("哈", "笑毛&qu ...
- Java替换字符串中的占位符
在开发中,会有动态配置字符串其中的某些字符,如何使用字符中的占位符,并且在代码动态替换占位符实现动态配置字符串! 1.定义字符串时,再string文件添加字符串: 注意!记得要在字符文件中加上这些: ...
- java:替换字符串中的ASCII码
可对照查看网盘ASCII表http://yunpan.cn/cyxg4wQjQaGEQ (提取码:8b29) public static void main(String[] args) { // / ...
- java替换字符串中的World为Money
public class Money{ public static void main(String[] args) { String a = "Hello Java World\n&quo ...
- java 替换字符串中的中括号
正确方式:"[adbdesf]".replaceAll("\\[", "").replaceAll("\\]", &qu ...
- Java替换字符串中的\r\n
public static void main(String[] args) { String str = "啊\r\n啊"; str = str.replaceAll(" ...
- Java-Runoob-高级教程-实例-字符串:04. Java 实例 - 字符串替换
ylbtech-Java-Runoob-高级教程-实例-字符串:04. Java 实例 - 字符串替换 1.返回顶部 1. Java 实例 - 字符串替换 Java 实例 如何使用java替换字符串 ...
- Python - 安全替换字符串模板(safe_substitute) 详细解释
安全替换字符串模板(safe_substitute) 详细解释 本文地址: http://blog.csdn.net/caroline_wendy/article/details/27057339 字 ...
- Python之word文档替换字符串(也可以用于短模板套用)
Python之word文档替换字符串(也可以用于短模板套用),代码如下: 1 ''' 2 #word模板套用1:创建模板,适合比较短的文档 3 ''' 4 5 #导入所需库 6 from docx i ...
随机推荐
- Linux系统(Centos)下安装Java环境配置步骤详述
1.首先要去下载好JDK,Java SE 8的官方网址是http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2 ...
- filename extension
题目描述 Please create a function to extract the filename extension from the given path,return the extra ...
- 运用Links方法安装插件
方法如下: (1)在Eclipse的安装目录下新建两个文件夹:一个用来存放插件,取名为myplugins:另一个用来存放link文件,取名为links. (2)将下载的插件解压缩到myplugins目 ...
- oracle 错误代码表
ORA-00001: 违反唯一约束条件 (.) ORA-00017: 请求会话以设置跟踪事件 ORA-00018: 超出最大会话数 ORA-00019: 超出最大会话许可数 ORA-00020: 超出 ...
- Codeforces Beta Round #25 (Div. 2 Only)D. Roads not only in Berland
D. Roads not only in Berland time limit per test 2 seconds memory limit per test 256 megabytes input ...
- bzoj3137: [Baltic2013]tracks
炸一看好像很神仙的样子,其实就是个sb题 万年不见的1A 但是我们可以反过来想,先选一个起点到终点的联通块,然后这联通块后面相当于就能够走了,继续找联通块 然后就能发现直接相邻的脚步相同的边权为0,否 ...
- 执行sql语句异常...需要的参数与提供的值个数不匹配
执行mysql语句时,出现以下错误时. 看错误提示,提示说你的sql语句只需要5个参数,而你提供了8个值value,你确定你确实需要8个参数,而你的sql语句却提示说只需要5个参数 这时,请仔细检查一 ...
- codeforces 443 B. Kolya and Tandem Repeat 解题报告
题目链接:http://codeforces.com/contest/443/problem/B 题目意思:给出一个只有小写字母的字符串s(假设长度为len),在其后可以添加 k 个长度的字符,形成一 ...
- Python(2)(基本输入输出语句)
我们先来说输出:
- Linux系统中的运行级别
什么是运行级呢?简单的说,运行级就是操作系统当前正在运行的功能级别. 它让一些程序在一个级别启动,而另外一个级别的时候不启动. Linux系统的有效登录模式有0~9共十种,不过沿用UNIX系统的至多6 ...