简体   繁体   English

Java 生成带占位符的字符串

[英]Java generating Strings with placeholders

I'm looking for something to achieve the following:我正在寻找可以实现以下目标的东西:

String s = "hello {}!";
s = generate(s, new Object[]{ "world" });
assertEquals(s, "hello world!"); // should be true

I could write it myself, but It seems to me that I saw a library once which did this, probably it was the slf4j logger, but I don't want to write log messages.我可以自己写,但在我看来,我曾经看到一个图书馆这样做,可能是 slf4j 记录器,但我不想写日志消息。 I just want to generate strings.我只想生成字符串。

Do you know about a library which does this?你知道做这件事的图书馆吗?

See String.format method.请参阅String.format方法。

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

StrSubstitutor from Apache Commons Lang may be used for string formatting with named placeholders:来自 Apache Commons Lang 的StrSubstitutor可用于使用命名占位符进行字符串格式化:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.1</version>
</dependency>

https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html : https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html

Substitutes variables within a string by values.用值替换字符串中的变量。

This class takes a piece of text and substitutes all the variables within it.该类采用一段文本并替换其中的所有变量。 The default definition of a variable is ${variableName}.变量的默认定义是 ${variableName}。 The prefix and suffix can be changed via constructors and set methods.可以通过构造函数和 set 方法更改前缀和后缀。

Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.变量值通常从映射解析,但也可以从系统属性解析,或通过提供自定义变量解析器。

Example:例子:

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);

This can be done in a single line without the use of library.这可以在不使用库的情况下在一行中完成。 Please check java.text.MessageFormat class.请检查java.text.MessageFormat类。

Example例子

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");

Output will be输出将是

test String with placeholders place-holder-1 place-holder-2 place-holder-3 place-holder-4

If you can change the format of your placeholder, you could use String.format() .如果您可以更改占位符的格式,则可以使用String.format() If not, you could also replace it as pre-processing.如果没有,您也可以将其替换为预处理。

String.format("hello %s!", "world");

More information in this other thread . 此其他线程中的更多信息。

There are two solutions:有两种解决方案:

Formatter is more recent even though it takes over printf() which is 40 years old... Formatter是更新的,即使它接管了已有 40 年历史的printf() ......

Your placeholder as you currently define it is one MessageFormat can use, but why use an antique technique?您当前定义的占位符是MessageFormat可以使用的一种,但为什么要使用古老的技术? ;) Use Formatter . ;) 使用Formatter

There is all the more reason to use Formatter that you don't need to escape single quotes!使用Formatter的更多理由是您不需要转义单引号! MessageFormat requires you to do so. MessageFormat要求您这样做。 Also, Formatter has a shortcut via String.format() to generate strings, and PrintWriter s have .printf() (that includes System.out and System.err which are both PrintWriter s by default)此外, Formatter有一个通过String.format()生成字符串的快捷方式,而PrintWriter s 有.printf() (包括System.outSystem.err ,默认情况下都是PrintWriter s)

You won't need a library;你不需要图书馆; if you are using a recent version of Java, have a look at String.format :如果您使用的是最新版本的 Java,请查看String.format

String.format("Hello %s!", "world");

If you can tolerate a different kind of placeholder (ie %s in place of {} ) you can use String.format method for that:如果您可以容忍不同类型的占位符(即%s代替{} ),您可以使用String.format方法:

String s = "hello %s!";
s = String.format(s, "world" );
assertEquals(s, "hello world!"); // true

if you are user spring you can like this:如果你是用户 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);

out put:输出:

hello world

Justas answer is outdated so I'm posting up to date answer with apache text commons. Justas 的答案已过时,因此我将使用 apache text commons 发布最新答案。

StringSubstitutor from Apache Commons Text may be used for string formatting with named placeholders: https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html来自 Apache Commons Text 的StringSubstitutor可用于使用命名占位符进行字符串格式化: https : StringSubstitutor

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

This class takes a piece of text and substitutes all the variables within it.该类采用一段文本并替换其中的所有变量。 The default definition of a variable is ${variableName}.变量的默认定义是 ${variableName}。 The prefix and suffix can be changed via constructors and set methods.可以通过构造函数和 set 方法更改前缀和后缀。 Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.变量值通常从映射解析,但也可以从系统属性解析,或通过提供自定义变量解析器。

Example:例子:

 // 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);

The suggestion by https://stackoverflow.com/users/4290127/himanshu-chaudhary works quite well: String str = "Hello this is {} string {}"; https://stackoverflow.com/users/4290127/himanshu-chaudhary的建议效果很好: String str = "Hello this is {} string {}";
str = MessageFormatter.format(str, "hello", "world").getMessage(); 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");

Java is most likely going to have string templates (probably from version 21 ). Java 很可能会有字符串模板(可能从版本21开始)。

See the string templates proposal (JEP 430) here .在此处查看字符串模板提案 (JEP 430)

It will be something along the lines of this:这将是这样的:

String name = "World";
String info = STR."Hello \{name}!";
System.out.println(info); // Hello World!

PS Kotlin is 100% interoperable with Java. PS Kotlin与 Java 100% 互操作。 It supports cleaner string templates out of the box:它支持开箱即用的更清晰的字符串模板:

val name = "World"
val info = "I am $name!"
println(info) // Hello World!

Combined with extension functions , you can achieve the same thing the Java template processors (eg STR ) will do.结合扩展功能,您可以实现 Java 模板处理器(例如STR )将做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM