字符串替换参数一般是先解析出参数名字,然后替换掉,可以使用正则替换,也可以使用拼接字符串的方式替换,下面的代码代码演示了2种情况下如何替换参数,一种是参数名称含前缀和后缀如${key},另一种情况是只含前缀,使用空格作为后缀,如:key,代码如下:
package com.huse.strtest; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Set; public class 字符串替换参数小结_S4_Test { public static void main(String[] args) throws Exception { 字符串替换参数小结_S4_Test t = new 字符串替换参数小结_S4_Test(); String str = "$ { name},${name },$ {${order}} ${${$}"; String beforSplit = "${"; String afterSplit = "}"; Map<String, String> context = new HashMap<String, String>(); context.put("name", "测试\\${"); context.put("order", "测试值\\$1"); context.put("${$", "测试值\\$2"); System.out.println("#-------------测试有前缀有后缀------------------#"); System.out.println("采用正则拿到${key}后替换:"); System.out.println(t.replaceAllStrByRegNormal(str, beforSplit,afterSplit, context)); System.out.println("采用字符串查找先取到所有key再直接replaceAll"); System.out.println(t.replaceAllStrByReg(str, beforSplit, afterSplit,context)); System.out.println("使用StringBuffer拼接替换字符串后的结果,采用subString得到${key}后替换"); System.out.println(t.replaceAllStrByAppendStr(str, beforSplit,afterSplit, context)); System.out.println("#-------------测试有前缀空格后缀------------------#"); String str2 = "A: :A 测试:A :B C :D :E :F F: in( :m ,:l"; context.put("A", "测试$:"); context.put("B", "测试$2"); context.put("D", "测试$3"); context.put("F", "测试\\$4"); context.put("l", "测试5"); beforSplit = ":"; System.out.println("采用正则拿到:key后替换"); System.out.println(t.replaceAllStrByRegNormal2(str2, beforSplit, context)); System.out.println("采用字符串查找先取到所有key再直接replaceAll"); System.out.println(t.replaceAllStrByReg2(str2, beforSplit,context)); System.out.println("使用StringBuffer拼接替换字符串后的结果,采用subString得到${key}后替换"); System.out.println(t.replaceAllStrByAppendStr2(str2, beforSplit,context)); } /** * @Description 采用正则拿到${key}后替换 */ public String replaceAllStrByRegNormal(String str, String beforSplit, String afterSplit, Map<String, String> paramData) throws Exception { // 参数校验 if (paramData == null || paramData.size() == 0) { return str; } if (isEmptyStr(str)) { return null; } if (isEmptyStr(beforSplit)) { beforSplit = "${"; } if (isEmptyStr(afterSplit)) { afterSplit = "}"; } //不匹配时候原样输出 String tmpBeforSplit = beforSplit, tmpAfterSplit = afterSplit; beforSplit = beforSplit.replaceAll("\\$", "\\\\\\$"); beforSplit = beforSplit.replaceAll("\\{", "\\\\\\{"); afterSplit = afterSplit.replaceAll("\\$", "\\\\\\$"); afterSplit = afterSplit.replaceAll("\\{", "\\\\\\{"); String regex = beforSplit + "(.+?)" + afterSplit; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String key = matcher.group(1);// 键名 String value = (String) paramData.get(trimStr(key));// 键值 if (value == null) { value = tmpBeforSplit + key + tmpAfterSplit;// 如果不想保留不匹配值则value="" } value = java.util.regex.Matcher.quoteReplacement(value); matcher.appendReplacement(sb, value); } matcher.appendTail(sb); return sb.toString(); } /** * @Description 采用字符串查找先取到所有key再直接replaceAll ${key} */ public String replaceAllStrByReg(String str, String beforSplit, String afterSplit, Map<String, String> context) { // 参数校验 if (context == null || context.size() == 0) { return str; } if (isEmptyStr(str)) { return null; } if (isEmptyStr(beforSplit)) { beforSplit = "${"; } if (isEmptyStr(afterSplit)) { afterSplit = "}"; } Map<String, String> resultMap = safetyProcessMapValue(context); Set<String> paramNames = getParamNames(str, beforSplit, afterSplit); for (String name : paramNames) { Object obj = resultMap.get(trimStr(name)); if (obj != null) { String regex = "\\Q" + beforSplit + name + afterSplit + "\\E"; str = str.replaceAll(regex, obj.toString()); } } return str; } /** * @Description 根据分割符从字符串中取得变量的名字 */ public Set<String> getParamNames(String str, String beforeSplit, String afterSplit) { Set<String> paramNames = new HashSet<String>(); int start = 0, end = 0; while (end < str.length()) { start = str.indexOf(beforeSplit, end); if (start == -1) { break; } start = start + beforeSplit.length(); end = str.indexOf(afterSplit, start); if (end == -1) { break; } String param = str.substring(start, end); paramNames.add(param); end = end + afterSplit.length(); } return paramNames; } /** * @Description: 使用StringBuffer拼接替换字符串后的结果,采用subString得到${key}替换 适用于key * 2侧都有值 */ public String replaceAllStrByAppendStr(final String str, String beforSplit, String afterSplit, Map<String, String> map) { if (map == null || map.size() == 0) { return str; } if (isEmptyStr(str)) { return null; } if (isEmptyStr(beforSplit)) { beforSplit = "${"; } if (isEmptyStr(afterSplit)) { afterSplit = "}"; } StringBuilder sb = new StringBuilder((int) (str.length() * 1.5)); int cursor = 0; for (int start, end; (start = str.indexOf(beforSplit, cursor)) != -1 && (end = str.indexOf(afterSplit, start)) != -1;) { sb.append(str.substring(cursor, start)); String key = str.substring(start + beforSplit.length(), end); if (map.get(trimStr(key)) != null) { sb.append(map.get(trimStr(key))); } else { sb.append(beforSplit).append(key).append(afterSplit); } cursor = end + 1; } sb.append(str.substring(cursor, str.length())); return sb.toString(); } /** * @Description 采用正则拿到:key后替换 */ public String replaceAllStrByRegNormal2(String str, String beforSplit, Map<String, String> paramData) throws Exception { // 参数校验 if (paramData == null || paramData.size() == 0) { return str; } if (isEmptyStr(str)) { return null; } if (isEmptyStr(beforSplit)) { beforSplit = ":"; } beforSplit = beforSplit.replaceAll("\\$", "\\\\\\$"); beforSplit = beforSplit.replaceAll("\\{", "\\\\\\{"); String regex = beforSplit + "([^\\s]+?)" + "(\\s+|$)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String key = matcher.group(1);// 键名 String value = (String) paramData.get(trimStr(key));// 键值 if (value == null) { value = matcher.group(0); } else { value = value + " "; } value = java.util.regex.Matcher.quoteReplacement(value); matcher.appendReplacement(sb, value); } matcher.appendTail(sb); return sb.toString(); } /** * @Description 拿到所有:key后replaceAll */ public String replaceAllStrByReg2(String str, String beforSplit, Map<String, String> context) { // 参数校验 if (context == null || context.size() == 0) { return str; } if (isEmptyStr(str)) { return null; } if (isEmptyStr(beforSplit)) { beforSplit = ":"; } Map<String, String> resultMap = safetyProcessMapValue(context); Set<String> paramNames = getParamNames2(str, beforSplit); for (String name : paramNames) { Object obj = resultMap.get(trimStr(name)); if (obj != null) { String regex = "\\Q" + beforSplit + name + "\\E"; str = str.replaceAll(regex, obj.toString()); } } return str; } public Set<String> getParamNames2(String str, String beforeSplit) { Set<String> paramNames = new HashSet<String>(); int start = 0, end = 0; while (end < str.length()) { start = str.indexOf(beforeSplit, end); if (start == -1) { break; } start = start + beforeSplit.length(); end = str.indexOf(" ", start); if (end == -1) { end = str.lastIndexOf(beforeSplit); if (end != start-beforeSplit.length()) { break; } end = str.length(); } String param = str.substring(start, end); paramNames.add(param); end = end + " ".length(); } return paramNames; } /** * @Description StringBuilder 拼接 */ public String replaceAllStrByAppendStr2(final String str, String beforSplit, Map<String, String> map) { if (map == null || map.size() == 0) { return str; } if (isEmptyStr(str)) { return null; } if (isEmptyStr(beforSplit)) { beforSplit = ":"; } StringBuilder sb = new StringBuilder((int) (str.length() * 1.5)); int cursor = 0; for (int start, end; (start = str.indexOf(beforSplit, cursor)) != -1;) { end = str.indexOf(" ", start); if (end == -1) { if ((end=str.lastIndexOf(beforSplit)) != start) { break; } else { end = str.length(); } } sb.append(str.substring(cursor, start)); String key = str.substring(start + beforSplit.length(), end); if (map.get(trimStr(key)) != null) { sb.append(map.get(trimStr(key))).append(" "); } else { sb.append(beforSplit).append(key).append(" "); } cursor = end + 1; } if(cursor<=str.length()){ sb.append(str.substring(cursor, str.length())); } return sb.toString(); } public String trimStr(final String str) { return str == null ? null : str.trim(); } public boolean isEmptyStr(String str) { return str == null || str.trim().length() == 0; } // 对特殊字符进行处理如$ public Map<String, String> safetyProcessMapValue(Map<String, String> map) { Map<String, String> resultMap = new HashMap<String, String>(); for (Entry<String, String> entry : map.entrySet()) { resultMap.put(entry.getKey(), java.util.regex.Matcher.quoteReplacement(entry.getValue())); } return resultMap; } }
结果为:
#-------------测试有前缀有后缀------------------# 采用正则拿到${key}后替换: $ { name},测试\${,$ {测试值\$1} 测试值\$2 采用字符串查找先取到所有key再直接replaceAll $ { name},测试\${,$ {测试值\$1} 测试值\$2 使用StringBuffer拼接替换字符串后的结果,采用subString得到${key}后替换 $ { name},测试\${,$ {测试值\$1} 测试值\$2 #-------------测试有前缀空格后缀------------------# 采用正则拿到:key后替换 A: 测试$: 测试测试$: 测试$2 C 测试$3 :E 测试\$4 F: in( :m ,测试5 采用字符串查找先取到所有key再直接replaceAll A: 测试$: 测试测试$: 测试$2 C 测试$3 :E 测试\$4 F: in( :m ,测试5 使用StringBuffer拼接替换字符串后的结果,采用subString得到${key}后替换 A: 测试$: 测试测试$: 测试$2 C 测试$3 :E 测试\$4 F: in( :m ,测试5
转载请注明原处,原链接http://53873039oycg.iteye.com/blog/2144339,谢谢。
全文完。