2016-05-13 159 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