0

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

gusaindpk
  • 1,243
  • 2
  • 13
  • 31
  • What do you mean by "replacing the exact string"? It's really unclear what you're trying to achieve. – Jon Skeet Jul 03 '13 at 07:40
  • Show an example with a string constant which works. – Thorbjørn Ravn Andersen Jul 03 '13 at 07:40
  • @Thorbjørn Ravn Andersen exact string menas Ex: I want to replace a world "test" to "notest" in a given string say "test1 test" the output will be "test1 notest". The mytext.replaceAll('\\b('+text+')\\b',"testtest"); code works fine for the normal word(like "test")but not for word containing # or @(like "@test" or "#test") – gusaindpk Jul 03 '13 at 07:46
  • Explain yourself better and update your question – surfealokesea Jul 03 '13 at 07:55

2 Answers2

1

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);
surfealokesea
  • 4,971
  • 4
  • 28
  • 38
0

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.

Michael Lang
  • 3,902
  • 1
  • 23
  • 37
  • thanks it worked can you give me any link where I can check something more about regex it would be helpfull – gusaindpk Jul 03 '13 at 09:09
  • 2
    Or (as you're using Groovy): `replaceAll( /(^|\W)($text)($|\W)/, "\$1$replacement\$3")` – tim_yates Jul 03 '13 at 10:26
  • @gusaindpk Regarding your problem at hand: see [this](http://www.regular-expressions.info/wordboundaries.html) and [this](http://stackoverflow.com/questions/4213800/is-there-something-like-a-counter-variable-in-regular-expression-replace/4214173#4214173) Generally, (http://www.regular-expressions.info/) contains most of the information you will need. – Michael Lang Jul 03 '13 at 10:28