Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named placeholders in string formatting

People also ask

What is placeholder string?

In computer programming, a placeholder is a character, word, or string of characters that temporarily takes the place of the final data. For example, a programmer may know that she needs a certain number of values or variables, but doesn't yet know what to input.

How do you replace a placeholder in a string?

You can easily use it to replace placeholders by name with this single method call: StringUtils. replaceEach("There's an incorrect value '%(value)' in column # %(column)", new String[] { "%(value)", "%(column)" }, new String[] { x, y });

How do you add a placeholder to a string in Java?

printf("%d %d", 42, 23); We've put two %d symbols in the template String. These two symbols represent placeholders for a certain type of value. For instance, the %d is a placeholder for a decimal numeric value.

What is a Java placeholder?

A Placeholder is a predefined location in a JSP that displays a single piece of web content at a time that is dynamically retrieved from the BEA Virtual Content Repository.


StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly.

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

The above results in:

"There's an incorrect value '1' in column # 2"

When using Maven you can add this dependency to your pom.xml:

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

not quite, but you can use MessageFormat to reference one value multiple times:

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

The above can be done with String.format() as well, but I find messageFormat syntax cleaner if you need to build complex expressions, plus you dont need to care about the type of the object you are putting into the string


Another example of Apache Common StringSubstitutor for simple named placeholder.

String template = "Welcome to {theWorld}. My name is {myName}.";

Map<String, String> values = new HashMap<>();
values.put("theWorld", "Stackoverflow");
values.put("myName", "Thanos");

String message = StringSubstitutor.replace(template, values, "{", "}");

System.out.println(message);

// Welcome to Stackoverflow. My name is Thanos.

You can use StringTemplate library, it offers what you want and much more.

import org.antlr.stringtemplate.*;

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