當前位置:名人名言大全網 - 短信平臺 - Java字符串模板的替換問題,我是初學者,老師沒講集合。請問怎麽做?

Java字符串模板的替換問題,我是初學者,老師沒講集合。請問怎麽做?

import java.util.Properties;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class StringUtils {

public static String composeMessage(String template,Properties data) throws Exception {

Pattern p = Pattern.compile("\\$\\{(\\w+)\\}", Pattern.MULTILINE);

Matcher m = p.matcher(template);

while (m.find()) {

template = template.replace(m.group(), data.getProperty(m.group(1)));

}

return template;

}

/**

* @param args

*/

public static void main(String[] args) {

String template="尊敬的客戶${customerName}妳好!本次消費金額${amount},您帳戶${accountNumber}上的余額為${balance}";

Properties prop = new Properties();

prop.put("customerName", "張三");

prop.put("amount", "10");

prop.put("accountNumber", "No.123456");

prop.put("balance", "80.5");

try {

System.out.println(composeMessage(template, prop));

} catch (Exception e) {

e.printStackTrace();

}

}

}

//利用正則表達式,匹配妳的變量