Replace characters in java string

66 views Asked by At

I am trying to replace the following text in some HTML:

[merchant]

I tried to use myString = myString.replace("\\[merchant\\]", "newText");

The string is not being replaced. Any ideas?

3

There are 3 answers

1
Reimeus On BEST ANSWER

replace doesnt use a regular expression. Just use

myString = myString.replace("[merchant]", "newText");
0
Razib On

Try this -

    String myString = "My Sampel String [merchant]. Another line with [merchant]";
    myString = myString.replace("[merchant]", "newText");

    System.out.println(myString);  

You don't have to use \\ here.

0
Mureinik On

String#replace uses string literals, not regexes, so you shouldn't escape any special characters like [ or ]:

myString = myString.replace("[merchant]", "newText");