Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing contents inside curly braces (for e.g. {1}) with something else [duplicate]

Tags:

java

string

I have a string as follows

Hey {1}, you are {2}.

Here 1 and 2 are key whose value will be added dynamically.

Now I need to replace {1} with the value that 1 represents and then I need to replace {2} with the value that 2 represents in the sentence above.

How do I do it?

I know what split function of a string does and I know very well that with that function I can do what I want but I am looking for something better.

Note: I don't know what these keys are in advance. I need to retrieve the keys as well. And then according to the keys I need to replace the values in the string.

like image 801
Smrita Avatar asked Jun 17 '14 05:06

Smrita


People also ask

How do you escape curly braces in Python?

Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }} .

How do you escape curly braces in PHP?

Simply write the expression the same way as it would appear outside the string, and then wrap it in { and } . Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the { .

What is the purpose of {} squiggly braces in Java?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.


2 Answers

You can use MessageFormat from java.text.MessageFormat. Message Format has some example on how it can be used in this type of scenario

like image 51
Pranav Maniar Avatar answered Sep 19 '22 15:09

Pranav Maniar


Thanks to https://stackoverflow.com/users/548225/anubhava for this one.. :). You could do something like this:

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

}

Output:

Hey one, you are two.
like image 32
TheLostMind Avatar answered Sep 18 '22 15:09

TheLostMind