Java: 如何使用 Map<String,String> 填充文本中的占位符?

Java: How to fill placeholders in a text with Map<String,String>?

我正在处理一个代码,我想用另一个字符串填充几个字符串占位符。这是我用来测试代码的示例文本。

String myStr = "Media file %s of size %s has been approved"

这就是我填充占位符的方式。因为我希望使用多个占位符,所以我使用了 java Map<>.

Map<String, String> propMap = new HashMap<String,String>();
propMap.put("file name","20mb");
String newNotification = createNotification(propMap);

我使用以下方法创建字符串。

public String createNotification(Map<String, String> properties){
    String message = ""; 
    message = String.format(myStr, properties);

    return message;
}

如何将“%s”中的两个替换为 "file name" 和“20mb”?

您对 String#format 的处理方式是错误的。

它需要可变数量的对象来替换占位符作为第二个参数,而不是地图。要将它们组合在一起,您可以使用数组或列表。

String format = "Media file %s of size %s has been approved";

Object[] args = {"file name", "20mb"};
String newNotification = String.format(format, args);

这不是 Map 的目的。 您添加的是条目 "file name" -> "20 mb",这基本上意味着 属性 "file name" 的值为“20 mb”。你想用它做什么是 "maintain a tuple of items".

请注意,格式字符串具有固定数量的占位符;你想要一个包含完全相同数量项目的数据结构;所以本质上是一个数组或 List.

所以,你想要的是

public String createNotification(String[] properties) {
    assert(properties.length == 2); // you might want to really check this, you will run into problems if it's false
    return String.format("file %s has size %s", properties);
}

如果你想创建地图中所有项目的通知,你需要做这样的事情:

Map<String,String> yourMap = //...
for (Entry<String,String> e : yourMap) {
    System.out.println(createNotification(e.getKey(), e.getValue()));
}

我认为%s是Python的占位符语法,不能在Java环境下使用;而且你的方法createNotification()定义需要两个参数,不能只给一个。

您可以简单地使用 var-args 进行格式化:

    String myStr = "Media file %s of size %s has been approved";

    String newNotification = createNotification(myStr, "file name", "20mb");

    System.out.println(newNotification);

createNotification方法中传递可变参数,这里是代码:

public static String createNotification(String myStr, String... strings){
    String message = ""; 
    message=String.format(myStr, strings[0], strings[1]);

    return message;
}

在尝试了多种方法后终于找到了一个很好的解决办法。占位符必须像这样 [placeholder] .

public String createNotification(){
    Pattern pattern = Pattern.compile("\[(.+?)\]");
    Matcher matcher = pattern.matcher(textTemplate);
    HashMap<String,String> replacementValues = new HashMap<String,String>();
    StringBuilder builder = new StringBuilder();
    int i = 0;
    while (matcher.find()) {
        String replacement = replacementValues.get(matcher.group(1));
        builder.append(textTemplate.substring(i, matcher.start()));
        if (replacement == null){ builder.append(matcher.group(0)); }      
        else { builder.append(replacement); }     
        i = matcher.end();
    }
    builder.append(textTemplate.substring(i, textTemplate.length()));
    return builder.toString()
}