Java – replace the contents in curly braces with something else (e.g. {1}) [copy]
•
Java
See English answers > java: string formatting with placeholders 3
Hey {1},you are {2}.
Here 1 and 2 are keys whose values will be added dynamically
Now I need to replace {1} with the value represented by 1, and then I need to replace {2} with the value represented by 2 in the above sentence
What shall I do?
I know what the string segmentation function is. I know very well that through this function, I can do what I want to do, but I'm looking for something better
Note: I don't know what these keys are in advance I also need to retrieve the key Then I need to replace the value in the string according to the key
Solution
thank https://stackoverflow.com/users/548225/anubhava This...:) You can do 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.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码