我有一个HashMap,里面有键和值。我想用字符串中的映射值替换键。
在字符串中,键被写成这个@keyName或@"keyName" --它们应该被替换为
我们的地图是这样的
"key1" : "2"
"key2" : "3"
"key3" : "4"
"key 4" : "5"
"key-5" : "6"所以,如果我们处理字符串“你好世界,我是@key1 1岁”,,它将变成“你好世界,我2岁”。
我们可以使用@key1代替@"key1"。如果我们使用它没有引号,空格(空格字符)或EOF应该在键名后面,键名不应该有空格。但是如果键名中有一个空格,那么它应该是引号。
如果我们处理字符串"hello world,我是@"key@"key1"“几岁”。,在第一步,它应该取代特殊字符串中的特殊字符串,成为"hello world,I‘am @"key2“。”,然后第二步应该是"hello world,我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.发布于 2016-11-22 16:20:48
我在这里做了一个与你的例子相匹配的正则表达式: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;
}更新
regex:https://regex101.com/r/nudYEl/4
@(\"[\w\s-]+\")|(?!@([\w-]+)@([\w-]+))@([\w-]+)
发布于 2016-11-22 14:47:04
不要使用regex:
for (boolean hit = true; hit;) {
hit = false;
for (String key : map.keySet()) {
if (str.contains("@\"" + key + "\"")) {
str = str.replace("@\"" + key + "\"", map.get(key));
hit = true;
} else if (str.contains("@" + key )) {
str = str.replace("@" + key + "", map.get(key));
hit = true;
}
}
}https://stackoverflow.com/questions/40744325
复制相似问题