我有一个字符串和一个映射,如下所述:
我想使用我的地图中存在的值替换花括号中的值(如果地图中存在相应的键,则保持不变)。
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);