[英]Replace exact string with special characters and not the part of another substring
我正在嘗試從類似的字符串中替換子字符串:
Sample string value '[1]T.1.v - Marriage Statement'!C10 and this
替換為'[1]T.1.v - Marriage Statement'!C10
的文本,並加上其他字符串,例如var1
以便該字符串成為Sample string value var1 and this
。 問題是可能存在一些字符串,例如Sample string value '[1]T.1.v - Marriage Statement'!C101 and this
在此替換不起作用。 我正在探索邊界正則表達式一詞來限制替換:
String sample = "Value can be '[1]T.1.v - Marriage Statement'!C10 and this";
String a = sample.replaceAll("\\b'[1]T.1.v - Marriage Statement'!C10\\b", "var1");
System.out.println(a);
但這似乎並不能完全取代這個詞。 我嘗試了簡單的字符串替換,但是它將替換Sample string value '[1]T.1.v - Marriage Statement'!C101 and this
的子字符串, Sample string value '[1]T.1.v - Marriage Statement'!C101 and this
同時將輸出作為Sample string value var11 and this
是一個錯誤。
有什么建議可以實現嗎?
刪除前導\\b
然后使用\\Q...\\E
轉義序列將輸入字符串視為文字:
String a = sample.replaceAll("\\Q" + param +"\\E\\b", "var1");
轉義括號和點
'\[1\]T\.1\.v - Marriage Statement'!C10
兩件事情:
•將您的replaceAll
\\\\'
更改為\\'
•將replaceAll(...
更改為replace(...
(請參閱文章底部)
它看起來應該像這樣:
public static void main(String[]args) {
String sample = "Value can be '[1]T.1.v - Marriage Statement'!C10 and this";
String a = sample.replace("\'[1]T.1.v - Marriage Statement\'!C10", "var1");
System.out.println(a);
}
產生輸出:
Value can be var1 and this
如果要替換一堆出現的東西(例如字母A),則使用replaceAll
會更好。如果只是替換一個實例,那么replace
會很好地替換某些東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.