import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author wuwuwuu
* @version 1.0
* @date 2022/10/13
*/
public class format
{
public static void main(String[] args) {
String text = "count exceeding. The account[uuid: 12345678910] exceeds a count[name: handsomeBoy, value: 3]. Please " +
"contact the administrator.";
String format = "count exceeding. The account[uuid: {0}] exceeds a count[name: {1}, value: {2}]. Please contact the administrator.";
String display = "参数1:{0},参数2:{1},参数3:{2}";
System.out.println(reFormat(format,text,display));
}
private static String reFormat(String regex, String text, String displayMessage) {
//{0-9}替换成(.+)
regex = regex.replaceAll("\\{([0-9])*\\}", "(.+)");
// 特殊化处理[符号
regex = regex.replaceAll("\\[", "\\\\[");
Matcher m = Pattern.compile(regex).matcher(text);
String[] paramVars = null;
if (m.find()) {
int count = m.groupCount();
paramVars = new String[count];
int start = 1;
while (start <= count) {
paramVars[start - 1] = (m.group(start++));
}
return MessageFormat.format(displayMessage, paramVars);
}
return text;
}
}
运行结果: