[英]How to replace exact string containing characters @ and # in java
嗨,我在替換包含#和@字符的確切字符串時遇到麻煩。 我嘗試了mytext.replaceAll('\\\\b('+text+')\\\\b',"testtest");
也,但也沒有幫助。 確切的字符串表示確切的單詞。
String myStr = "test1 test";
myStr= myStr.replaceAll('\\b('+ Pattern.quote("test") +')\\b',"notest")//out put string "test1 notest"
//Exact word means only "test" is getting replace not "test" from "test1" word to notest1
String myStr1 = "test1 #test";
myStr1 = myStr1.replaceAll('\\b('+Pattern.quote("#test") +')\\b',"notest")//out put string "test1 #test", #test is not replaced
有人可以幫幫我嗎。 提前致謝
您有幾個編譯錯誤。
這段代碼為我工作:
String myStr = "test1 test";
myStr= myStr.replaceAll("\\b("+ Pattern.quote("test") +")\\b","notest");
System.out.println(myStr);
String myStr1 = "test1 #test";
myStr1 = myStr1.replaceAll("\\b("+Pattern.quote("#test") +")\\b","notest");
System.out.println(myStr);
我認為您想要的是:
mytext.replaceAll("(^|\\W)("+text+")($|\\W)", "$1"+replacement+"$3"))
解決方案中\\b
的問題在於,它僅與[a-zA-Z0-9_]
和#
以及@
匹配,而不是將它們分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.