问题

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

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

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


#1 热门回答(111 赞)

如果你的值已经正确格式化,那么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>

#2 热门回答(48 赞)

不完全,但你可以使用MessageFormat多次引用一个值:

MessageFormat.format("There's an incorrect value \"{0}\" in column # {1}", x, y);

以上也可以使用String.format()完成,但是如果你需要构建复杂的表达式,我发现messageFormat语法更清晰,而且你不需要关心你放入字符串的对象的类型


#3 热门回答(11 赞)

你可以使用StringTemplatelibrary,它提供你想要的东西等等。

import org.antlr.stringtemplate.*;

final StringTemplate hello = new StringTemplate("Hello, $name$");
hello.setAttribute("name", "World");
System.out.println(hello.toString());

原文链接