替换字符串中的多个子字符串 [英] replace multiple sub-strings in a string

查看:208
本文介绍了替换字符串中的多个子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This function is used to replace certain substrings in a string with respective values.

// map(string_to_replace,string_to_replace_with)

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

如果要替换的子字符串被(空格)包围,以上功能将正常工作。

This above function works fine if substring to be replaced is surrounded by " "(space).

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

Ex- String => "Hey {how} are $=you" if substrings to be replaced is "Hey" or "you", then it works fine. The issue is when I want to replace "how" and "you".

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

How can I achieve this without additional complexity ?

推荐答案

我想只替换您在地图上的单词,并保留其余的字样,您可以继续如下:

I you want to replace only the words that you have in the map and keep the rest as it is, you can proceed as next:

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} ,您将需要动态创建正则表达式:

Assuming that you want to be able to replace not only words but anything like ${questionNumber}, you will need to create the regular expression dynamically like this:

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

这篇关于替换字符串中的多个子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆