有没有简单的方法可以替换字符串中所有出现的(整个)单词?我目前正在使用它,它不是很优雅:
public static String replace(String input, String toReplace,
String replacement){
if(input==null) throw new NullPointerException();
input = input.replace(" "+toReplace+" ", " "+replacement+" ");
input = input.replaceAll("^"+toReplace+" ", replacement+" ");
input = input.replaceAll(" "+toReplace+"$", " "+replacement);
return input;
}
此外,正则表达式"^"+toReplace+" "
不是正则表达式安全的。例如:当它可能包含诸如[
或之类的字符时(
。
编辑:
这段代码的任何原因:
public static String replace(String input, String toReplace,
String replacement){
if(input==null) throw new NullPointerException();
input = input.replace(" "+toReplace+" ", " "+replacement+" ");
input = input.replaceAll(Pattern.quote("^"+toReplace+" "), replacement+" ");
input = input.replaceAll(Pattern.quote(" "+toReplace+"$"), " "+replacement);
//input = input.replaceAll("\\b" + Pattern.quote(toReplace) + "\\b", replacement);
return input;
}
在以下情况下表现这种方式:
input = "test a testtest te[(st string test";
input = replace(input, toReplace, "REP");
System.out.println(input);
a)toReplace = test
打印:
test a testtest te[(st string test
b)toReplace = te[(st
打印:
test a testtest REP string test
谢谢,