mbrc
mbrc

Reputation: 3963

replace substring in string when string contains [] characters

I want to replace substringin string. For example:

localStringBuilder is for example "[sender] is xxxx xxxx xxx".

and when I run

localStringBuilder.toString().replaceAll("[sender]", callerName);

not working correctly. Prblem is with [] characters. How to solve this?

Upvotes: 3

Views: 19338

Answers (4)

Dan D.
Dan D.

Reputation: 32391

This works:

locaStringBuilder.toString().replaceAll("\\[sender\\]", callerName);

Upvotes: 0

Ransom Briggs
Ransom Briggs

Reputation: 3095

Use this

   localStringBuilder.toString().replaceAll("\\[sender\\]", callerName);

Upvotes: 0

dantuch
dantuch

Reputation: 9293

Just use replace in place of replaceAll

replaceAll take REGEX as input, not a String, but regex. [] are important parts of regexes using to group expressions.

localStringBuilder.toString().replace("[sender]", callerName); will work exaclty as you expect, because it takes normal Strings as both parameters.

is the same. Works when is no [] characters in string – @mbrc 1 min ago

not true, I've tested it:

public static void main(String[] args) {
    String s = "asd[something]123";
    String replace = s.replace("[something]", "new1");
    System.out.println(replace);
}

output: asdnew1123

Upvotes: 4

DJClayworth
DJClayworth

Reputation: 26876

replaceAll returns a new string with the replacement. It doesn't replace the characters in the original string.

String newString = localStringBuilder.toString().replaceAll("[sender]", callerName);

Upvotes: 0

Related Questions