繁体   English   中英

通过对应哈希图中存在的名称值来替换字符串中的id值

[英]replace id value in a string by corresonding name values whuch are present in a hashmap

我有一个字符串和一个映射,如下所述:

我想使用我的地图中存在的值替换花括号中的值(如果地图中存在相应的键,则保持不变)。

String input = "[text{100}any text1({200})text2{300}{400}{500}not{600}]";
Map<String,String> map = new HashMap<>();
map.put("{100}", "hundred");
map.put("{200}", "two hundred");
map.put("{300}", "three hundred");
map.put("{400}", "four hundred");
map.put("{500}", "five hundred");

我想要输出为字符串,应该像这样:

"[text hundred any text1 (two hundred) text2 three hundred,four hundred,five hundred not{600}]"

我的代码是:

String uuidString = "[text{100}any text1({200})text2{300}{400}{500}not{600}]";

Map<String,String> map = new HashMap<>();
map.put("{100}", "hundred");
map.put("{200}", "two hundred");
map.put("{300}", "three hundred");
map.put("{400}", "four hundred");
map.put("{500}", "five hundred");

String[] uuidList = uuidString.split("(?=\\{)|(?<=\\})");
String uuidValue;


for(int i=0;i<uuidList.length;i++){
    uuidValue = map.get(uuidList[i]);
    if(uuidValue != null){
        uuidList[i]=uuidValue;
    }
}
uuidString = Arrays.toString(uuidList);
System.out.println("string :"+uuidString);

我的输出:

string :[[text, hundred, any text1(, two hundred, )text2, three hundred, four hundred, five hundred, not, {600}, ]] but

我只需要连续大括号的逗号,并希望输出如下:

string :[[text hundred any text1 (two hundred) text2 three hundred, four hundred, five hundred not{600} ]]

只需搭配

\{\d+?\}

在哈希中找到相应的值,并将上面的匹配项替换为找到的值。

String uuidString = "[text{100}any text1({200})text2{300}{400}{500}not{600}]";

Map<String,String> map = new HashMap<>();
map.put("{100}", "hundred");
map.put("{200}", "two hundred");
map.put("{300}", "three hundred");
map.put("{400}", "four hundred");
map.put("{500}", "five hundred");

Pattern numberInCurlyBrackets = Pattern.compile("\\{\\d+?\\}");
Matcher matcher = numberInCurlyBrackets.matcher(uuidString);

while(matcher.find()) {
    String replacee = matcher.group();
    String replacement = map.get(replacee);
    if (replacement != null)
        uuidString = uuidString.replace(replacee, replacement);
}
System.out.println(uuidString);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM