我有一个字符串和一张地图,如下所述:
我想使用地图中存在的值替换花括号中的值(如果地图中存在相应的键,则保持相同)。
void main()
{
Stack *S = new Stack;
char val;
while(true)
{
cout<<"enter character:"<<endl;
cin>>val;
S->push(val);
}
S->pop();
}
我希望输出为字符串,应该是:
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
答案 0 :(得分:0)
只需与
匹配\{\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);