【发布时间】:2013-03-25 03:37:32
【问题描述】:
有没有简单的方法可以替换字符串中所有出现的(整个)单词?我目前正在使用它,它不是很优雅:
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
谢谢,
【问题讨论】:
-
你有什么问题?你的期望是什么?你得到了什么?
-
我有两个期望:a) 如果我们正则表达式安全,则替换为替换。 b) 代码经济(也许是一行代码)。
-
正则表达式安全是什么意思?
-
如果你不想在你的正则表达式模式中允许正则表达式特殊字符,你为什么要使用正则表达式呢?使用用户输入字符串作为正则表达式模式表明您应该重新考虑您的方法。