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.
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 }} .
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 { .
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.
You can use MessageFormat from java.text.MessageFormat. Message Format has some example on how it can be used in this type of scenario
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With