[英]Replace placeholders with Map values using indexOf
我正在嘗試使用indexOf在字符串(“ $ {...}”)中查找占位符。 到目前為止,我下面的小示例效果很好,但顯然僅適用於首次出現。 我如何更改此代碼以能夠遍歷所有占位符並最終重建String。 輸入的String可以是隨機的,並且其中沒有固定數量的占位符。 不太確定從這里去哪里。
// example Hashmap
HashMap <String, String> placeHolderMap = new HashMap<String, String>();
placeHolderMap.put("name", "device");
placeHolderMap.put("status", "broken");
placeHolderMap.put("title", "smartphone");
// input String
String content = "This ${name} is ${status} and categorized as ${title} in the system";
int left = content.indexOf("${");
int right = content.indexOf("}");
// getting the name of the placeholder, if the placeholdermap contains the placeholder as a key it sets the placeholder to the corresponding value
String contentPlaceHolder = content.substring(left+2, right);
if (placeHolderMap.containsKey(contentPlaceHolder)){
contentPlaceHolder = placeHolderMap.get(contentPlaceHolder);
}
content = content.substring(0, left) + contentPlaceHolder + content.substring(right+1);
當前,輸出為“此設備為$ {status},在系統中歸類為$ {title}”。
為什么不使用String.replaceAll()方法?
Map<String, String> placeHolderMap = new HashMap<>();
placeHolderMap.put("\\$\\{name}", "device");
placeHolderMap.put("\\$\\{status}", "broken");
placeHolderMap.put("\\$\\{title}", "smartphone");
// input String
String content = "This ${name} is ${status} and categorized as ${title} in the system";
for (Map.Entry<String, String> entry : placeHolderMap.entrySet()) {
content = content.replaceAll(entry.getKey(), entry.getValue());
}
更新 Stefan,Neil和Kennet,謝謝。
更新17/07/17您還可以使用不使用正則表達式的String.replace()方法,或者使用Pattern.quote()方法:
Map<String, String> placeHolderMap = new HashMap<>();
placeHolderMap.put("${name}", "device");
placeHolderMap.put("${status}", "broken");
placeHolderMap.put("${title}", "smartphone");
// input String
String content = "This ${name} is ${status} and categorized as ${title} in the system";
for (Map.Entry<String, String> entry : placeHolderMap.entrySet()) {
content = content.replace(entry.getKey(), entry.getValue());
// content = content.replaceAll(Pattern.quote(entry.getKey()), entry.getValue());
}
您需要回溯地調用方法:
private String replace(String content) {
int left = content.indexOf("${");
if (left < 0) {
// breaking the recursion
return content;
}
int right = content.indexOf("}");
// getting the name of the placeholder, if the placeholdermap contains the placeholder as a key it sets the placeholder to the corresponding value
String contentPlaceHolder = content.substring(left + 2, right);
if (placeHolderMap.containsKey(contentPlaceHolder)) {
contentPlaceHolder = placeHolderMap.get(contentPlaceHolder);
}
content = content.substring(0, left) + contentPlaceHolder + content.substring(right + 1);
return replace(content);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.