java通过regex更改包含{n}的String

时间:2013-05-22 14:08:08

标签: java regex

我有一个包含像{0},{1} ...... {n}这样的表达式的String。我有一个n长度的字符串列表。 {0}替换为param [0],{1}替换为param [1],{n}替换为param [n]。我怎么能这样做?

List<String> params = new ArrayList<String>;
param[0] = "dortmund";
param[1] = "5555";
String message = "customers address is  {0}, phone number is {1}, please check them.";

2 个答案:

答案 0 :(得分:6)

您可以使用MessageFormat

MessageFormat messageFormat = new MessageFormat("customers address is  {0}, phone number is {1}, please check them.");
Object[] args = {"dortmund", "5555"};
String message = messageFormat.format(args);

答案 1 :(得分:-1)

for (int i=0; i < params.size(); ++i) {
    message = message.replace("{"+i+"}", params[i]);
}