使用 indexOf 将占位符替换为地图值

Replace placeholders with Map values using indexOf

我正在尝试使用 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);

目前,输出为 "This device is ${status} and categorized as ${title} in the system"

您需要递归调用一个方法:

private String replace(String content) {
    int left = content.indexOf("${");
    if (left < 0) {
        // breaking the recursion
        return content;
    }
    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);
    return replace(content);
}

你为什么不使用 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,谢谢。

更新 17/07/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());
    }