2016-05-13 161 views
3

该函数用于用相应的值替换字符串中的某些子字符串。替换字符串中的多个子字符串

//地图(string_to_replace,string_to_replace_with)

String template = "ola ala kala pala sala"; 
StringBuilder populatedTemplate = new StringBuilder(); 
HashMap<String, String> map = new HashMap<>(); 
map.put("ola", "patola"); 
map.put("pala", "papala"); 

int i=0; 
for (String word : template.split("'")) { 
    populatedTemplate.append(map.getOrDefault(word, word)); 
    populatedTemplate.append(" "); 
} 

System.out.println(populatedTemplate.toString()); 

此上述功能工作正常,如果要被替换字符串为““(空格)所包围。

Ex- String =>“嘿{how} are $ = you” 如果要替换的子字符串是“嗨”或“你”,那么它工作正常。问题是我想要替换“如何”和“你”。

如何在不增加复杂度的情况下实现这一目标?

+0

为什么不'template.replace(string_to_replace,string_to_replace_with)'往往你需要? PS:http://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regexes可能工作,否则。 – zapl

+0

@zapl这个问题与替换是相关的。即让我想将“如何”替换为“是”,将“是”替换为“OK”。在第一次迭代之后,字符串将是“嘿,你是$你”。并在第二次迭代“嘿{ok}确定$ =你”之后。指出错误的输出。它应该是“嗨,你好”$ =你“ – tarun14110

回答

2

我要替换只是你在地图上,并保持休息,因为它是的话,你可以继续为下一个:

String template = "Hey {how} are $=you"; 
StringBuilder populatedTemplate = new StringBuilder(); 
Map<String, String> map = new HashMap<>(); 
map.put("how", "HH"); 
map.put("you", "YY"); 
// Pattern allowing to extract only the words 
Pattern pattern = Pattern.compile("\\w+"); 
Matcher matcher = pattern.matcher(template); 
int fromIndex = 0; 
while (matcher.find(fromIndex)) { 
    // The start index of the current word 
    int startIdx = matcher.start(); 
    if (fromIndex < startIdx) { 
     // Add what we have between two words 
     populatedTemplate.append(template, fromIndex, startIdx); 
    } 
    // The current word 
    String word = matcher.group(); 
    // Replace the word by itself or what we have in the map 
    populatedTemplate.append(map.getOrDefault(word, word)); 
    // Start the next find from the end index of the current word 
    fromIndex = matcher.end(); 
} 
if (fromIndex < template.length()) { 
    // Add the remaining sub String 
    populatedTemplate.append(template, fromIndex, template.length()); 
} 
System.out.println(populatedTemplate); 

输出:

Hey {HH} are $=YY 

回复更新:

假设您希望能够替换不仅单词而且ything像${questionNumber},您将需要动态创建的正则表达式是这样的:

String template = "Hey {how} are $=you id=minScaleBox-${questionNumber}"; 
... 
map.put("${questionNumber}", "foo"); 
StringBuilder regex = new StringBuilder(); 
boolean first = true; 
for (String word : map.keySet()) { 
    if (first) { 
     first = false; 
    } else { 
     regex.append('|'); 
    } 
    regex.append(Pattern.quote(word)); 
} 
Pattern pattern = Pattern.compile(regex.toString()); 
... 

输出:

Hey {HH} are $=YY id=minScaleBox-foo 
+0

让字符串=>”id = minScaleBox - $ {questionNumber}“,toreplaceString =”$ {questionNumber}“。在这种情况下,它不起作用。可以做到吗? – tarun14110

+0

回复更新 –

+0

非常感谢,这正是我需要的 – tarun14110