我有一个HashMap,里面有键和值。我想用字符串中的映射值替换键。
在字符串中,键写为此@keyName或@“ keyName”,应将其替换为map.get(“ keyName”)
可以说我们的地图是这个
"key1" : "2"
"key2" : "3"
"key3" : "4"
"key 4" : "5"
"key-5" : "6"
因此,如果我们处理字符串“ hello world,我今年@ key1岁。”,它将变成“ hello world,我今年2岁”。
代替@ key1,我们可以使用@“ key1”。如果我们在不带引号的情况下使用它,则键名后面应包含空格(空格字符)或EOF,并且键名中不应包含空格。但是,如果键名中有空格,则应在引号中。
并且,如果我们处理字符串“ hello world,我是@“ key @” key1“”岁。”,则第一步应替换特殊字符串中的特殊字符串,并成为“ hello world,我是@“ key2”。岁。”然后第二步应该是“你好,我今年3岁”。
我已经为一个特殊字符串完成了此操作,它无法识别特殊字符串中的特殊字符串。这是代码:
private static Pattern specialStringPattern = Pattern.compile("@\"([^\"]*?)\"|@\\S+");
/** this replaces the keys inside a string with their values.
* for example @keyName or @"keyName" is replaced with the value of the keyName. */
public static String specialStrings(String s) {
Matcher matcher = specialStringPattern.matcher(s);
while (matcher.find()) {
String text = matcher.group();
text = text.replace("@","").replaceAll("\"","");
s = s.replace(matcher.group(),map.get(text));
}
return s;
}
很抱歉,我的英语水平以及我对Regex的了解不足。我认为通过一点点修改代码来获得答案应该很容易。
这是我需要的一些例子:
There is @key1 apples on the table.
There is 2 apples on the table.
There is @"key1" apples on the table.
There is 2 apples on the table.
There is @key 4 apples on the table.
There is null 4 apples on the table.
There is @"key 4" apples on the table.
There is 5 apples on the table.
There is @key@key2 apples on the table.
There is @key3 apples on the table. (second step)
There is 4 apples on the table. (final output)
There is @"key @"key3"" apples on the table.
There is @"key 4" apples on the table. (second step)
There is 5 apples on the table. (final output)
There is @"key @key3" apples on the table.
There is @"key 4" apples on the table. (second step)
There is 5 apples on the table. (final output)
There is @"key @key3 " apples on the table.
There is @"key 4 " apples on the table. (second step)
There is null apples on the table. (final output)
There is @key-5 apples on the table.
There is 6 apples on the table.
最佳答案
我做了正则表达式,以匹配您的示例在这里:
https://regex101.com/r/nudYEl/2@(\"[\w\s]+\")|(?!@(\w+)@(\w+))@(\w+)
并且您只需要将函数修改为递归即可:
public static String specialStrings(String s) {
Matcher matcher = specialStringPattern.matcher(s);
boolean findAgain = false;
while (matcher.find()) {
String text = matcher.group();
text = text.replace("@","").replaceAll("\"","");
s = s.replace(matcher.group(),map.get(text));
findAgain = true;
}
if (findAgain) return specialStrings(s);
return s;
}
[更新]
正则表达式:https://regex101.com/r/nudYEl/4
@(\"[\w\s-]+\")|(?!@([\w-]+)@([\w-]+))@([\w-]+)