簡體   English   中英

Java:替換多個字符串占位符的最快方法

[英]Java: Fastest way to replace multiple string placeholder

用Java替換多個占位符的最快方法是什么。

例如:我有一個帶有多個占位符的字符串,每個都有一個字符串占位符名稱。

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

還有一個Map,其中包含將在哪個占位符中放置什么值的地圖。

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

用Java替換Map中所有占位符的最快方法是什么。 是否可以一次性更新所有占位符?

(請注意,我無法將占位符格式更改為{1},{2}等)

您可以嘗試使用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 );

您可以使用以下方法進行操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM