简体   繁体   中英

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)

You can try with StrSubstitutor (Apache Commons)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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