字符串格式中的命名占位符

新手上路,请多包涵

在 Python 中,格式化字符串时,我可以按名称而不是按位置填充占位符,如下所示:

 print "There's an incorrect value '%(value)s' in column # %(column)d" % \
  { 'value': x, 'column': y }

我想知道这在 Java 中是否可行(希望没有外部库)?

原文由 Andy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 640
2 个回答

感谢你的帮助!使用您的所有线索,我编写了例程来完全按照我的意愿行事——使用字典进行类似 python 的字符串格式化。由于我是 Java 新手,因此感谢任何提示。

 public static String dictFormat(String format, Hashtable<String, Object> values) {
    StringBuilder convFormat = new StringBuilder(format);
    Enumeration<String> keys = values.keys();
    ArrayList valueList = new ArrayList();
    int currentPos = 1;
    while (keys.hasMoreElements()) {
        String key = keys.nextElement(),
        formatKey = "%(" + key + ")",
        formatPos = "%" + Integer.toString(currentPos) + "$";
        int index = -1;
        while ((index = convFormat.indexOf(formatKey, index)) != -1) {
            convFormat.replace(index, index + formatKey.length(), formatPos);
            index += formatPos.length();
        }
        valueList.add(values.get(key));
        ++currentPos;
    }
    return String.format(convFormat.toString(), valueList.toArray());
}

原文由 Andy 发布,翻译遵循 CC BY-SA 3.0 许可协议

jakarta commons lang 的 StrSubstitutor 是一种轻量级的方法,前提是您的值已经正确格式化。

http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html

 Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");

上面的结果是:

“第 2 列中的值‘1’不正确”

使用 Maven 时,您可以将此依赖项添加到您的 pom.xml 中:

 <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

原文由 schup 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题