Java字符串格式化,{}占位符根据名字替换实例

时间:2021-05-20

我就废话不多说了,大家还是直接看代码吧~

import java.beans.PropertyDescriptor;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;public class StringFormatUtil { private static final Pattern pattern = Pattern.compile("\\{(.*?)\\}"); private static Matcher matcher; /** * 格式化字符串 字符串中使用{key}表示占位符 * * @param sourStr * 需要匹配的字符串 * @param param * 参数集 * @return */ public static String stringFormat(String sourStr, Map<String, Object> param) { String tagerStr = sourStr; if (param == null) return tagerStr; try { matcher = pattern.matcher(tagerStr); while (matcher.find()) { String key = matcher.group(); String keyclone = key.substring(1, key.length() - 1).trim(); Object value = param.get(keyclone); if (value != null) tagerStr = tagerStr.replace(key, value.toString()); } }catch (Exception e){ return null; } return tagerStr; } /** * 格式化字符串 字符串中使用{key}表示占位符 利用反射 自动获取对象属性值 (必须有get方法) * * @param sourStr 需要匹配的字符串 * * @return */ public static String stringFormat(String sourStr, Object obj) { String tagerStr = sourStr; matcher = pattern.matcher(tagerStr); if (obj == null) return tagerStr; PropertyDescriptor pd; Method getMethod; // 匹配{}中间的内容 包括括号 while (matcher.find()) { String key = matcher.group(); String keyclone = key.substring(1, key.length() - 1).trim(); try { pd = new PropertyDescriptor(keyclone, obj.getClass()); getMethod = pd.getReadMethod();// 获得get方法 Object value = getMethod.invoke(obj); if (value != null) tagerStr = tagerStr.replace(key, value.toString()); } catch (Exception e) { // TODO Auto-generated catch block // Loggers.addException(e); } } return tagerStr; } /** * 格式化字符串 (替换所有) 字符串中使用{key}表示占位符 * * @param sourStr * 需要匹配的字符串 * @param param * 参数集 * @return */ public static String stringFormatAll(String sourStr, Map<String, Object> param) { String tagerStr = sourStr; if (param == null) return tagerStr; try { matcher = pattern.matcher(tagerStr); while (matcher.find()) { String key = matcher.group(); String keyclone = key.substring(1, key.length() - 1).trim(); Object value = param.get(keyclone); if (value != null) tagerStr = tagerStr.replace(key, value.toString()); } }catch (Exception e){ return null; } return tagerStr; } /** * 格式花字符串,按照占位符名字 * 输入:sourStr = xxxxx{a}xxxx{b} ,param = {a:A,b:B} * 输出:targetStr = xxxxAxxxxB * @param sourStr * @param param * @return */ public static String stringFormat(String sourStr, JSONObject param) { String tagerStr = sourStr; if (param == null) return tagerStr; try { matcher = pattern.matcher(tagerStr); while (matcher.find()) { String key = matcher.group(); String keyclone = key.substring(1, key.length() - 1).trim(); Object value = param.get(keyclone); if (value != null) tagerStr = tagerStr.replace(key, value.toString()); } }catch (Exception e){ return null; } return tagerStr; } public static void main(String[] args) {// Map<String,Object> map = new HashMap<>();// map.put("id","111");// map.put("sss","ss");// JSONObject json = new JSONObject();// json.put("id","212");// json.put("fff","xxxx");// json.put("emmmmm",11);// stringFormat("sisas&{fff}_diwahwi%{id}{jio}",json); }}

补充知识:java中占位符的使用

二话不说,先上代码

package com.string.format;public class StringFormat { //占位符%s,拼接sql,删除两个表中的数据,条件是字符串数组类型的id public static void formSql(String tableName,String tableName2,String...strings){ //sql占位符 %s占位符 String sql="delete from %s,%s where id in (%s)"; //声明新的字符串 String sqls=""; //遍历字符串的参数数组 for (String str : strings) { //将参数数组拼接成字符串,用逗号分割 sqls += str + ","; } //拼接最后会多出个逗号,截取 sqls=sqls.substring(0, sqls.length()-1); //format第一个sql参数为目标字符串,tableName,tableName2,为替换的两表的名字,sqls为删除数据的参数集合 String s=String.format(sql, tableName,tableName2,sqls); //输出拼接后的sql System.out.println(s); } public static void main(String[] args) { //传入参数为指定表名,和参数值 StringFormat.formSql("user","role", "1","3","5","7","9","33"); }}

其实,传入的参数是数组类型的 值,我们也可以按array[0],array[1]的方式插入参数,只是参数个数应用不灵活,还是使用数组的方式取值比较好,

public static void format(){ String st="%s的%s的价格是%f,是否售罄%c,占总销售的%d%%,库存%d,是否为畅销品%b"; String s=String.format(st, "58优品","啤酒",3.5,'是',50,199,true); System.out.println(s); } public static void main(String[] args) { //传入参数为指定表名,和参数值 //StringFormat.formSql("user","role", "1","3","5","7","9","33"); format(); }public static void format(){ //String st="%s的%s的价格是%f,是否售罄%c,占总销售的%d%%,库存%d,是否为畅销品%b"; //String s=String.format(st, "58优品","啤酒",3.5,'是',50,199,true); //System.out.println(s); SimpleDateFormat simple=new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒"); String newDate=simple.format(new Date()); String st1="%s的%s的价格是%s,是否售罄%s,占总销售的%s%%,库存%s,是否为畅销品%s,当前日期为%s"; String ss=String.format(st1, "58优品","啤酒","3.5",'是',"80","998","true",newDate); System.out.println(ss); } public static void main(String[] args) { //传入参数为指定表名,和参数值 //StringFormat.formSql("user","role", "1","3","5","7","9","33"); format(); }/*%S字符串类型的占位符 * %c字符类型的占位符 * %b布尔类型的占位符 * %d整数类型的占位符 * %%百分比类型的占位符 * %n换行类型的占位符 * %t时间类型的占位符 * c全部的日期时间类型 * F年-月-日格式 * D年/月/日格式 * rHH:MM:SS格式12小时制 * */

以上这篇Java字符串格式化,{}占位符根据名字替换实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章