![](/img/trans.png)
[英]how to replace all occurences of a word in a string with another word in java?
[英]Replace all occurences of a word in a string using regex
有沒有簡單的方法來替換字符串中所有出現的(整個)單詞? 我目前正在使用它,它不是很優雅:
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
print:
test a testtest REP string test
謝謝,
使用單詞邊界\\b
和Pattern.quote
進行轉義。
return input.replaceAll("\\b" + Pattern.quote(toReplace) + "\\b", replacement);
什么\\\\b
表示單詞和非單詞字符之間的零寬度邊界,包括字符串的開頭和結尾。
字邊界有一個特殊的正則表達式代碼 - \\b
。 這涵蓋了空間/行結尾的手動處理以及標點符號等其他情況。
有一個方法Pattern.quote()
引用字符串來保護regexp特殊內部,正如你所建議的那樣,如果字符串是任意的或者可能是用戶提供的話,應該總是使用它。
所以這給了:
input.replaceAll("\\b"+Pattern.quote(toReplace)+"\\b", replacement);
input = input.replaceAll("\\b"+Pattern.quote(toReplace)+"\\b", replacement);
\\ b匹配單詞邊界,請參閱http://www.regular-expressions.info/wordboundaries.html
使用java.util.regex.Pattern.quote來轉義特殊字符。
你需要知道正則表達式\\b
,它是“單詞邊界”的零寬度匹配。 有了它,你的方法的人變成了一行:
return input.replaceAll("\\b"+Pattern.quote(toReplace)+"\\b", replacement);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.