Tamanna_24
Tamanna_24

Reputation: 113

Java: Fastest way to replace multiple string placeholder

What is the fastest way in java to replace multiple placeholders.

For example: I have a String with multiple placeholder, each has string placeholder name.

String testString = "Hello {USERNAME}! Welcome to the {WEBSITE_NAME}!";

And a Map which contains the map of what value will be placed in which placeholder.

Map<String, String> replacementStrings = Map.of(
                "USERNAME", "My name",
                "WEBSITE_NAME", "My website name"
        );

What is the fastest way in java to replace all the placeholder from Map. Is it possible to update all placeholders in one go?

(Please note, I cannot change the placeholder format to {1}, {2} etc)

Upvotes: 9

Views: 14096

Answers (2)

Vikas
Vikas

Reputation: 7165

You can use StrSubstitutor class from Apache Commons Lang library:

String testString = "Hello {USERNAME}! Welcome to the {WEBSITE_NAME}!";
Map<String, String> replacementStrings = Map.of(
                "USERNAME", "My name",
                "WEBSITE_NAME", "My website name"
        );
StrSubstitutor sub = new StrSubstitutor(replacementStrings , "{", "}");
String result = sub.replace(testString );

UPDATE 2024

Since Apache Commons Lang version 3.6 StrSubstitutor is deprecated and replaced with the StringSubstitutor class from another library - Apache Commons Text.

Upvotes: 16

user9065831
user9065831

Reputation:

You can use below method to do so:

public static String replacePlaceholderInString(String text, Map<String, String> map){
    Pattern contextPattern = Pattern.compile("\\{[\\w\\.]+\\}");
    Matcher m = contextPattern .matcher(text);
    while(m.find()){
        String currentGroup = m.group();
        String currentPattern = currentGroup.replaceAll("^\\{", "").replaceAll("\\}$", "").trim();
        String mapValue = map.get(currentPattern);
        if (mapValue != null){
            text = text.replace(currentGroup, mapValue);
        }
    }
    return text;
}

Upvotes: 0

Related Questions