这是我从网上找的一道题,关于正则表达式方面的,怎么处理?
字符串模板:
String template="尊敬的客户${customerName}你好!本次消费金额${amount},您帐户${accountNumber}上的余额为${balance}";
其中以 ${ 开始 } 结尾的为待替换的变量域。
数据存放于Map中,key为域名,value为域值。如:
Map--
customerName = 刘明
accountNumber = 888888888888888
balance = $1000000000000000000000.00
amount = $5000.00
请编写函数:
public static String composeMessage(String template, Map data) throw Exception
实现将任意模板字符串中的变量域,按域名替换为data中的域值。
例如,上例替换结果为:
"尊敬的客户刘明你好!本次消费金额$5000.00,您帐户888888888888888上的余额为$1000000000000000000000.00"
注:如果Map中找不到域值,以空字符串""替换。
下面的代码试我写的
public static String composeMessage(String template, Map data) throws Exception { String regex = "\\$|\\{([^}]*)\\}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(template); StringBuffer sb = new StringBuffer(); while(matcher.find()) { String name = matcher.group(1); String value =(String)data.get(name); if(value==null) value=""; else value = value.replaceAll("\\$", "¥");//这句不加的话appendReplacement()这个方法回将$翻译成组 matcher.appendReplacement(sb,value); } matcher.appendTail(sb); return sb.toString(); }
import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Te { public static void main(String args[]) { HashMap<String, String> data = new HashMap<String, String>(); String template = "尊敬的客户${customerName}你好!本次消费金额${amount},您帐户${accountNumber}上的余额为${balance}"; data.put("customerName", "刘明"); data.put("accountNumber", "888888888888888"); data.put("balance", "$1000000000000000000000.00"); data.put("amount", "$5000.00"); try { System.out.println(composeMessage(template, data)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } data = null; template = null; } public static String composeMessage(String template, Map data) throws Exception { String regex = "\\$|\\{([^}]*)\\}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(template); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String name = matcher.group(1); String value = (String) data.get(name); if (value == null) value = ""; else value = value.replaceAll("\\$", "\\\\\\$");// 这句不加的话appendReplacement()这个方法回将$翻译成组 matcher.appendReplacement(sb, value); } matcher.appendTail(sb); return sb.toString(); }}