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

时间:2014-06-17 05:41:15

标签: java string

我有一个字符串如下

Hey {1}, you are {2}.

此处12是关键,其值将动态添加。

现在我需要将{1}替换为1代表的值,然后我需要将{2}替换为上面句子中2所代表的值。< / p>

我该怎么做?

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

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

5 个答案:

答案 0 :(得分:7)

您可以使用java.text.MessageFormat中的 MessageFormat Message Format有一些关于如何在这种情况下使用它的例子

答案 1 :(得分:6)

感谢https://stackoverflow.com/users/548225/anubhava这个...... :)。你可以这样做:

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);
    }

}

输出:

Hey one, you are two.

答案 2 :(得分:4)

尝试使用String.format()

String x = String.format("Hi %s, you are %s\n", str1, str2);

如果您已经有一个字符串"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");

答案 3 :(得分:4)

试试这个我认为这可以从我的问题中理解

public static void main(String[] args) {
       String str = "Hey {1} your {2} is {3}  clear to {4}  ";
       Map<Integer,String> map = new LinkedHashMap<Integer,String>();
       map.put(1, "Smrita");
       map.put(2, "question");
       map.put(3, "not");
       map.put(4, "anyone");
       while(str.contains("{")){
           Integer i = Integer.parseInt(str.substring(str.indexOf("{")+1, str.indexOf("{")+2));
           str = str.replace("{"+i+"}", map.get(i));

       }
        System.out.println(str);
    }

输出

Hey Smrita your question is not clear to anyone

答案 4 :(得分:0)

试试这个:

String str = "Hey {1}, you are {2}.";
str = str.replaceFirst("\\{.*?\\}", "Matt");

输出:

Hey Matt, you are {2}.

以上代码将替换{1}的第一个实例。如果您在循环中调用此序列替换代码中的键值,它将按照给定字符串中提到的顺序替换{...}中的所有字符串。