Named Placeholders in String Formatting – 在字符串格式化中命名的占位符

最后修改: 2022年 8月 16日

1. Overview


Java standard library provides the String.format() method to format a template-based string, such as: String.format(“%s is awesome”, “Java”).

Java标准库提供了String.format()方法来格式化一个基于模板的字符串,例如。String.format(“%s is awesome”, “Java”)

In this tutorial, we’ll explore how to make string formatting support named parameters.


2. Introduction to the Problem


The String.format() method is pretty straightforward to use. However, when the format() call has many arguments, it gets difficult to understand which value will come to which format specifier, for example:


Employee e = ...; // get an employee instance
String template = "Firstname: %s, Lastname: %s, Id: %s, Company: %s, Role: %s, Department: %s, Address: %s ...";
String.format(template, e.firstName, e.lastName, e.Id,, e.department, e.role ... )

Further, it’s error-prone when we pass those arguments to the method. For instance, in the example above, we put e.department ahead of e.role by mistake.


So, it would be great if we could use something like named parameters in the template and then apply formatting through a Map that holds all parameter name->value mappings:


String template = "Firstname: ${firstname}, Lastname: ${lastname}, Id: ${id} ...";
ourFormatMethod.format(template, parameterMap);

In this tutorial, we’ll first look at a solution using a popular external library, which can solve most cases of this problem. Then, we’ll discuss an edge case that breaks the solution.


Finally, we’ll create our own format() method to cover all cases.


For simplicity, we’ll use unit test assertions to verify if a method returns the expected string.


It’s also worth mentioning that we’ll only focus on simple string formats (%s) in this tutorial. Other format types, such as date, number, or a format with defined width and precision, are not supported.


3. Using StrSubstitutor From Apache Commons Text

3.使用StrSubstitutor来自Apache Commons Text

Apache Commons Text library contains many handy utilities for working with strings. It ships with StrSubstitutor, which allows us to do string substitution based on named parameters.

Apache Commons Text库包含许多用于处理字符串的便捷工具。它带有StrSubstitutor,它允许我们根据命名参数进行字符串替换。

First, let’s add the library as a new dependency to our Maven configuration file:



Of course, we can always find the latest version at the Maven Central repository.

当然,我们可以随时在Maven Central仓库找到最新版本

Before we see how to use the StrSubstitutor class, let’s create a template as an example:


String TEMPLATE = "Text: [${text}] Number: [${number}] Text again: [${text}]";

Next, let’s create a test to build a string based on the template above using StrSubstitutor:


Map<String, Object> params = new HashMap<>();
params.put("text", "It's awesome!");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}");
assertThat(result).isEqualTo("Text: [It's awesome!] Number: [42] Text again: [It's awesome!]");

As the test code shows, we let params hold all name -> value mappings. When we call the StrSubstitutor.replace() method, apart from template and params, we also pass the prefix and the suffix to inform StrSubstitutor what a parameter consists of in the template. StrSubstitutor will search prefix + map.entry.key + suffix for parameter names.

正如测试代码所示,我们让params持有所有name -> value的映射。当我们调用StrSubstitutor.replace()方法时,除了templateparams之外,我们还传递前缀和后缀来告知StrSubstitutor一个参数在模板中的组成StrSubstitutor将搜索prefix + map.entry.key + suffix的参数名称。

When we run the test, it passes. So, it seems that StrSubstitutor solves the problem.


4. An Edge Case: When Replacements Contain Placeholders


We’ve seen that the StrSubstitutor.replace() test passes for our basic use case. However, some special cases are not covered by the test. For example, the parameter value may contain the parameter name pattern “${ … }“.

我们已经看到,StrSubstitutor.replace()测试通过了我们的基本用例。然而,一些特殊情况并没有被测试所覆盖。例如,参数值可能包含参数名称模式”${ … }“。

Now, let’s test this case:


Map<String, Object> params = new HashMap<>();
params.put("text", "'${number}' is a placeholder.");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}");

assertThat(result).isEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]");

In the test above, the value of the parameter “${text}” contains the text “${number}“. So, we’re expecting that “${text}” is replaced by the text “${number}” literally.


However, the test fails if we execute it:


expected: "Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]"
 but was: "Text: ['42' is a placeholder.] Number: [42] Text again: ['42' is a placeholder.]"

So, StrSubstitutor treats the literal ${number} as a parameter placeholder, too.


In fact, StrSubstitutor‘s Javadoc has stated this case:


Variable replacement works in a recursive way. Thus, if a variable value contains a variable then that variable will also be replaced.


This happens because, in each recursion step, StrSubstitutor takes the last replacement result as the new template to proceed with further replacements.


To bypass this problem, we can choose different prefixes and suffixes so that they don’t get interfered with:


String TEMPLATE = "Text: [%{text}] Number: [%{number}] Text again: [%{text}]";
Map<String, Object> params = new HashMap<>();
params.put("text", "'${number}' is a placeholder.");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "%{", "}");

assertThat(result).isEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]");

However, theoretically speaking, as we cannot predict the values, it’s always possible that a value contains the parameter name pattern and interferes with the replacement.


Next, let’s create our own format() method to solve the problem.


5. Building the Formatter on Our Own


We’ve discussed why StrSubstitutor cannot handle the edge case well. So, if we create a method, the difficulty is that we shouldn’t use a loop or recursion to take the last step’s result as new input in the current step.


5.1. The Idea to Solve the Problem


The idea is that we search for the parameter name patterns in the template. However, when we find one, we don’t replace it with the value from the map immediately. Instead, we build a new template that can be used for the standard String.format() method. If we take our example, we will try to convert:


String TEMPLATE = "Text: [${text}] Number: [${number}] Text again: [${text}]";
Map<String, Object> params ...



String NEW_TEMPLATE = "Text: [%s] Number: [%s] Text again: [%s]";
List<Object> valueList = List.of("'${number}' is a placeholder.", 42, "'${number}' is a placeholder.");

Then, we can call String.format(NEW_TEMPLATE, valueList.toArray()); to finish the job.

然后,我们可以调用String.format(NEW_TEMPLATE, valueList.toArray());来完成工作。

5.2. Creating the Method


Next, let’s create a method to implement the idea:


public static String format(String template, Map<String, Object> parameters) {
    StringBuilder newTemplate = new StringBuilder(template);
    List<Object> valueList = new ArrayList<>();

    Matcher matcher = Pattern.compile("[$][{](\\w+)}").matcher(template);

    while (matcher.find()) {
        String key =;

        String paramName = "${" + key + "}";
        int index = newTemplate.indexOf(paramName);
        if (index != -1) {
            newTemplate.replace(index, index + paramName.length(), "%s");

    return String.format(newTemplate.toString(), valueList.toArray());

The code above is pretty straightforward. Let’s walk through it quickly to understand how it works.


First, we’ve declared two new variables to save the new template (newTemplate) and the value list (valueList). We’ll need them when we call String.format() later.

首先,我们声明了两个新的变量来保存新模板(newTemplate)和值列表(valueList)。当我们以后调用String.format() 时,我们将需要它们。

We use Regex to locate parameter name patterns in the template. Then, we replace the parameter name pattern with “%s” and add the corresponding value to the valueList variable.


Finally, we call String.format() with the newly converted template and values from valueList.


For simplicity, we’ve hard-coded the prefix “${” and suffixes “}” in the method. Also, if the value for a parameter “${unknown}” isn’t provided, we’ll simply replace the “${unknown}” parameter with “null.


5.3. Testing Our format() Method


Next, let’s test if the method works for the regular case:


Map<String, Object> params = new HashMap<>();
params.put("text", "It's awesome!");
params.put("number", 42);
String result = NamedFormatter.format(TEMPLATE, params);
assertThat(result).isEqualTo("Text: [It's awesome!] Number: [42] Text again: [It's awesome!]");

Again, the test passes if we give it a run.


Of course, we want to see if it works for the edge case, too:


params.put("text", "'${number}' is a placeholder.");
result = NamedFormatter.format(TEMPLATE, params);
assertThat(result).isEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]");

If we execute this test, it passes, too! We’ve solved the problem.


6. Conclusion


In this article, we’ve explored how to replace parameters in template-based strings from a set of values. Basically, Apache Commons Text’s StrSubstitutor.replace() method is pretty straightforward to use and can solve most cases. However, when values contain the parameter name patterns, StrSubstitutor may produce an unexpected result.

在这篇文章中,我们已经探讨了如何从一组值中替换基于模板的字符串中的参数。基本上,Apache Commons Text的StrSubstitutor.replace()方法使用起来相当直接,可以解决大多数情况。然而,当值包含参数名称模式时,StrSubstitutor可能会产生一个意外的结果。

Therefore, we’ve implemented a format() method to solve this edge case.


As always, the full source code of the examples is available over on GitHub.