我认为您不应该尝试找到更简单或更短的解决方案,而应该考虑您的方法的语义和效率。
您正在迭代一个可能没有指定迭代顺序的映射(如HashMap)并执行一个又一个替换,使用替换结果作为下一个的输入,由于先前应用的替换可能会丢失匹配项或替换替换内容中的内容。
即使我们假设您正在传递一个其键和值没有干扰的映射,这种方法也是非常低效的。进一步注意replaceAll 会将参数解释为正则表达式。
如果我们假设没有正则表达式,我们可以通过按长度对键进行排序来消除键之间的歧义,以便首先尝试更长的键。然后,执行单个替换操作的解决方案可能如下所示:
private static String replace(String text, Map<String, String> map) {
if(map.isEmpty()) return text;
String pattern = map.keySet().stream()
.sorted(Comparator.comparingInt(String::length).reversed())
.map(Pattern::quote)
.collect(Collectors.joining("|"));
Matcher m = Pattern.compile(pattern).matcher(text);
if(!m.find()) return text;
StringBuffer sb = new StringBuffer();
do m.appendReplacement(sb, Matcher.quoteReplacement(map.get(m.group())));
while(m.find());
return m.appendTail(sb).toString();
}
从 Java 9 开始,您可以在此处使用 StringBuilder 而不是 StringBuffer
如果你测试它
Map<String, String> map = new HashMap<>();
map.put("f", "F");
map.put("foo", "bar");
map.put("b", "B");
System.out.println(replace("foo, bar, baz", map));
你会得到
bar, Bar, Baz
证明替换 foo 优先于替换 f 并且其替换 bar 中的 b 未被替换。
如果您想要再次替换替换中的匹配项,则情况会有所不同。在这种情况下,您将需要一种控制顺序的机制或实现重复替换,只有在没有匹配项时才会返回。当然,后者需要注意提供替换,这些替换总是最终会收敛到一个结果。
例如
private static String replaceRepeatedly(String text, Map<String, String> map) {
if(map.isEmpty()) return text;
String pattern = map.keySet().stream()
.sorted(Comparator.comparingInt(String::length).reversed())
.map(Pattern::quote)
.collect(Collectors.joining("|"));
Matcher m = Pattern.compile(pattern).matcher(text);
if(!m.find()) return text;
StringBuffer sb;
do {
sb = new StringBuffer();
do m.appendReplacement(sb, Matcher.quoteReplacement(map.get(m.group())));
while(m.find());
m.appendTail(sb);
} while(m.reset(sb).find());
return sb.toString();
}
Map<String, String> map = new HashMap<>();
map.put("a", "e1");
map.put("e", "o2");
map.put("o", "x3");
System.out.println(replaceRepeatedly("foo, bar, baz", map));
fx3x3, bx321r, bx321z