Java中替换多个占位符的最快方法是什么?
例如:我有一个带有多个占位符的字符串,每个占位符都有字符串占位符名称。
String testString = "Hello {USERNAME}! Welcome to the {WEBSITE_NAME}!";
以及一个地图,其中包含将放置在哪个占位符中的值的地图。
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;
}