简体   繁体   English

如何在Java中替换包含字符@和#的确切字符串

[英]How to replace exact string containing characters @ and # in java

Hi I am getting trouble in replacing the exact string containing # and @ characters. 嗨,我在替换包含#和@字符的确切字符串时遇到麻烦。 I tried mytext.replaceAll('\\\\b('+text+')\\\\b',"testtest"); 我尝试了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. 解决方案中\\b的问题在于,它仅与[a-zA-Z0-9_]#以及@匹配,而不是将它们分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM