Hi I am getting trouble in replacing the exact string containing # and @ characters. I tried mytext.replaceAll('\\\\b('+text+')\\\\b',"testtest");
also but it also didn't helped. Exact string means the exact word.
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
Can some one please help me. Thanks in advance
You have several compilation errors.
This piece of code is working for me:
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);
I think what you want is:
mytext.replaceAll("(^|\\W)("+text+")($|\\W)", "$1"+replacement+"$3"))
The problem with \\b
in your solution is that it only matches [a-zA-Z0-9_]
and #
as well as @
separate your words instead of being included.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.