[英]Java generating Strings with placeholders
我正在寻找可以实现以下目标的东西:
String s = "hello {}!";
s = generate(s, new Object[]{ "world" });
assertEquals(s, "hello world!"); // should be true
我可以自己写,但在我看来,我曾经看到一个图书馆这样做,可能是 slf4j 记录器,但我不想写日志消息。 我只想生成字符串。
你知道做这件事的图书馆吗?
请参阅String.format
方法。
String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
来自 Apache Commons Lang 的StrSubstitutor
可用于使用命名占位符进行字符串格式化:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.1</version>
</dependency>
用值替换字符串中的变量。
该类采用一段文本并替换其中的所有变量。 变量的默认定义是 ${variableName}。 可以通过构造函数和 set 方法更改前缀和后缀。
变量值通常从映射解析,但也可以从系统属性解析,或通过提供自定义变量解析器。
例子:
String template = "Hi ${name}! Your number is ${number}";
Map<String, String> data = new HashMap<String, String>();
data.put("name", "John");
data.put("number", "1");
String formattedString = StrSubstitutor.replace(template, data);
这可以在不使用库的情况下在一行中完成。 请检查java.text.MessageFormat
类。
例子
String stringWithPlaceHolder = "test String with placeholders {0} {1} {2} {3}";
String formattedStrin = java.text.MessageFormat.format(stringWithPlaceHolder, "place-holder-1", "place-holder-2", "place-holder-3", "place-holder-4");
输出将是
test String with placeholders place-holder-1 place-holder-2 place-holder-3 place-holder-4
如果您可以更改占位符的格式,则可以使用String.format()
。 如果没有,您也可以将其替换为预处理。
String.format("hello %s!", "world");
此其他线程中的更多信息。
有两种解决方案:
Formatter
是更新的,即使它接管了已有 40 年历史的printf()
......
您当前定义的占位符是MessageFormat
可以使用的一种,但为什么要使用古老的技术? ;) 使用Formatter
。
使用Formatter
的更多理由是您不需要转义单引号! MessageFormat
要求您这样做。 此外, Formatter
有一个通过String.format()
生成字符串的快捷方式,而PrintWriter
s 有.printf()
(包括System.out
和System.err
,默认情况下都是PrintWriter
s)
你不需要图书馆; 如果您使用的是最新版本的 Java,请查看String.format
:
String.format("Hello %s!", "world");
如果您可以容忍不同类型的占位符(即%s
代替{}
),您可以使用String.format
方法:
String s = "hello %s!";
s = String.format(s, "world" );
assertEquals(s, "hello world!"); // true
如果你是用户 spring 你可以这样:
String template = "hello #{#param}";
EvaluationContext context = new StandardEvaluationContext();
context.setVariable("param", "world");
String value = new SpelExpressionParser().parseExpression(template, new TemplateParserContext()).getValue(context, String.class);
System.out.println(value);
输出:
hello world
Justas 的答案已过时,因此我将使用 apache text commons 发布最新答案。
来自 Apache Commons Text 的StringSubstitutor
可用于使用命名占位符进行字符串格式化: https : StringSubstitutor
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>
该类采用一段文本并替换其中的所有变量。 变量的默认定义是 ${variableName}。 可以通过构造函数和 set 方法更改前缀和后缀。 变量值通常从映射解析,但也可以从系统属性解析,或通过提供自定义变量解析器。
例子:
// Build map
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
// Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap);
// Replace
String resolvedString = sub.replace(templateString);
https://stackoverflow.com/users/4290127/himanshu-chaudhary的建议效果很好: String str = "Hello this is {} string {}";
str = MessageFormatter.format(str, "hello", "world").getMessage();
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta4</version>
</dependency>
如果你想对不同的占位符使用一些字符串,你可以使用这样的指针:
String.format("%1$s %2$s %1$s", "startAndEndText", "middleText");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.