如何在不拆分字符串的情况下用其他字符串替换字符串

How to replace a string with other strings without splitting the string

我有一个字符串

 String constantString="paramesh,ramesh,suresh";

我想用 venky 替换 paramesh,用 mahesh 替换 ramesh,用 fine 替换 suresh 等而不拆分字符串。

输出像:venky,mahesh,fine etc

如果你有多个替换要做,你可以将它们存储在 Map<String, String> 然后使用 String.replaceAll(String) 而不是 String.replace(String) 因为对我来说肯定不会在另一个里面有一个词(ramesh inside paramesh)你需要一个带有 \b 的正则表达式,这意味着 word boundPattern.quote() 在这里是为了防止有特殊字符会破坏正则表达式

Map<String, String> replacements = new HashMap<String, String>();
replacements.put("paramesh", "venky");
replacements.put("ramesh", "mahesh");
replacements.put("suresh", "fine");

String constantString="paramesh,ramesh,suresh";

for(Map.Entry<String,String> entry : replacements.entrySet()){
  constantString = constantString.replaceAll("\b" + Pattern.quote(entry.getKey()) + "\b", 
                                             entry.getValue());
}

Workable Demo