メッセージ curly brackets Number

oboe2uran.hatenablog.com

メソッド名が良くないので書き直す。

public static String getMessage(String template, Object...obj) {
    Objects.requireNonNull(template);
    String s = template;
    Matcher m = Pattern.compile("\\{\\d+\\}").matcher(template);
    while(m.find()){
        int n = Integer.parseInt(m.group().substring(1, m.group().length()-1));
        if (n < obj.length) {
            s = s.replace(m.group(), obj[n].toString());
        }
    }
    return s;
}

もしもテンプレートの置換文字 { 数字} が余ってると、

Strinf msg = getMessage("---{0}---{1}---{2}---", "A", "B");

の msg は、

---A---B---{2}---

になってしまう。
対象がなければ、空文字にしたく、

---A---B------

こうしたいのであれば、、

public static String getMessage(String template, Object...obj) {
    Objects.requireNonNull(template);
    String s = template;
    Matcher m = Pattern.compile("\\{\\d+\\}").matcher(template);
    while(m.find()){
        int n = Integer.parseInt(m.group().substring(1, m.group().length()-1));
        if (n < obj.length) {
            s = s.replace(m.group(), obj[n].toString());
        }else{
            s = s.replace(m.group(),"");
        }
    }
    return s;
}