用其他东西替换花括号内的内容(例如{1})

Smr*_*ita 3 java string

我有一个字符串如下

Hey {1}, you are {2}.
Run Code Online (Sandbox Code Playgroud)

这里12是关键将动态增加其价值.

现在我需要替换{1}1表示的值,然后我需要替换上面句子{2}2表示的值.

我该怎么做?

我知道字符串的分割功能是什么,我非常清楚,通过该功能,我可以做我想做的事,但我正在寻找更好的东西.

注意:我事先并不知道这些键是什么.我也需要检索密钥.然后根据键我需要替换字符串中的值.

Pra*_*iar 7

您可以使用java.text.MessageFormat中的MessageFormat. 消息格式有一些关于如何在此类场景中使用它的示例


The*_*ind 6

感谢/sf/users/38375781/这一个.. :).你可以这样做:

public static void main(String[] args) {
    String s = "Hey {1}, you are {2}.";
    HashMap<Integer, String> hm = new HashMap();
    hm.put(1, "one");
    hm.put(2, "two");
    Pattern p = Pattern.compile("(\\{\\d+\\})");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group());
        String val1 = m.group().replace("{", "").replace("}", "");
        System.out.println(val1);
        s = (s.replace(m.group(), hm.get(Integer.parseInt(val1))));
        System.out.println(s);
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

Hey one, you are two.
Run Code Online (Sandbox Code Playgroud)


Pab*_*lgo 5

尝试使用String.format()

String x = String.format("Hi %s, you are %s\n", str1, str2);
Run Code Online (Sandbox Code Playgroud)

如果你已经有一个字符串"Hey {1}, you are {2}.",你可以使用正则表达式替换{1}{2}使用%s

String template = "Hey {1}, you are {2}.";
String x = String.format(template.replaceAll("\\{\\d\\}", "%s"), "Name", "Surname");
Run Code Online (Sandbox Code Playgroud)