我正在尝试使用indexOf 来查找字符串中的占位符(“${...}”)。 到目前为止,我下面的小例子运行良好,但显然仅适用于第一次出现。我如何更改此代码才能遍历所有占位符并最终重建字符串。输入字符串可以是随机的,并且其中没有固定数量的占位符。不太确定从这里去哪里。
// example Hashmap
HashMap <String, String> placeHolderMap = new HashMap<String, String>();
placeHolderMap.put("name", "device");
placeHolderMap.put("status", "broken");
placeHolderMap.put("title", "smartphone");
// input String
String content = "This ${name} is ${status} and categorized as ${title} in the system";
int left = content.indexOf("${");
int right = content.indexOf("}");
// getting the name of the placeholder, if the placeholdermap contains the placeholder as a key it sets the placeholder to the corresponding value
String contentPlaceHolder = content.substring(left+2, right);
if (placeHolderMap.containsKey(contentPlaceHolder)){
contentPlaceHolder = placeHolderMap.get(contentPlaceHolder);
}
content = content.substring(0, left) + contentPlaceHolder + content.substring(right+1);
目前,输出为“此设备为 ${status},在系统中分类为 ${title}”
最佳答案
为什么不使用 String.replaceAll() 方法?
Map<String, String> placeHolderMap = new HashMap<>();
placeHolderMap.put("\\$\\{name}", "device");
placeHolderMap.put("\\$\\{status}", "broken");
placeHolderMap.put("\\$\\{title}", "smartphone");
// input String
String content = "This ${name} is ${status} and categorized as ${title} in the system";
for (Map.Entry<String, String> entry : placeHolderMap.entrySet()) {
content = content.replaceAll(entry.getKey(), entry.getValue());
}
更新Stefan、Neil 和 Kennet,谢谢。
更新 2017 年 7 月 17 日 您还可以使用不使用正则表达式的 String.replace() 方法,或者使用 Pattern.quote() 方法:
Map<String, String> placeHolderMap = new HashMap<>();
placeHolderMap.put("${name}", "device");
placeHolderMap.put("${status}", "broken");
placeHolderMap.put("${title}", "smartphone");
// input String
String content = "This ${name} is ${status} and categorized as ${title} in the system";
for (Map.Entry<String, String> entry : placeHolderMap.entrySet()) {
content = content.replace(entry.getKey(), entry.getValue());
// content = content.replaceAll(Pattern.quote(entry.getKey()), entry.getValue());
}
关于java - 使用 indexOf 将占位符替换为 Map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279378/