我正在尝试使用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}”
答案 0 :(得分:2)
为什么不使用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());
}
答案 1 :(得分:0)
您需要重复调用您的方法:
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);
}