替换字符串中的多个子字符串

时间:2016-05-13 19:06:40

标签: java string dictionary hashmap str-replace

此函数用于使用相应的值替换字符串中的某些子字符串。

// map(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());

如果要替换的子字符串被&#34;包围,则上述函数可以正常工作。 &#34;(空间)。

Ex- String =&gt; &#34;嘿{how}是$ =你&#34; 如果要替换的子串是&#34;嘿&#34;或者&#34;你&#34;,然后它工作正常。问题是当我想要替换&#34;如何&#34;和&#34;你&#34;。

如何在没有额外复杂性的情况下实现这一目标?

1 个答案:

答案 0 :(得分:3)

我想只替换地图中的单词并保持原样,您可以按下一步继续:

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

响应更新:

假设您希望不仅可以替换${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