Named placeholders in string formatting

后端 未结 20 2312
情话喂你
情话喂你 2020-11-27 10:16

In Python, when formatting string, I can fill placeholders by name rather than by position, like that:

print \"There\'s an incorrect value \'%(value)s\' in c         


        
20条回答
  •  天命终不由人
    2020-11-27 11:08

    public static String format(String format, Map values) {
        StringBuilder formatter = new StringBuilder(format);
        List valueList = new ArrayList();
    
        Matcher matcher = Pattern.compile("\\$\\{(\\w+)}").matcher(format);
    
        while (matcher.find()) {
            String key = matcher.group(1);
    
            String formatKey = String.format("${%s}", key);
            int index = formatter.indexOf(formatKey);
    
            if (index != -1) {
                formatter.replace(index, index + formatKey.length(), "%s");
                valueList.add(values.get(key));
            }
        }
    
        return String.format(formatter.toString(), valueList.toArray());
    }
    
    
    

    Example:

    String format = "My name is ${1}. ${0} ${1}.";
    
    Map values = new HashMap();
    values.put("0", "James");
    values.put("1", "Bond");
    
    System.out.println(format(format, values)); // My name is Bond. James Bond.
    

    提交回复
    热议问题