3

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?

mbrc
  • 3,523
  • 13
  • 40
  • 64

4 Answers4

4

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

dantuch
  • 9,123
  • 6
  • 45
  • 68
  • is the same. Works when is no [] characters in string – mbrc Aug 29 '12 at 19:07
  • @mbrc, no problem. I have to say that it's kind of sad, that among all those answers only mine suggested using `replace` here. Your problem wasn't wrong way of using regex, but JUST using it, when you probably didn't want to :) Adding `\\` wouldn't make your code better, it would just a hack to solve issue that shouldn't occur in the first place – dantuch Aug 29 '12 at 19:33
0

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);

DJClayworth
  • 26,349
  • 9
  • 53
  • 79
0

Use this

   localStringBuilder.toString().replaceAll("\\[sender\\]", callerName);
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
Ransom Briggs
  • 3,025
  • 3
  • 32
  • 46
0

This works:

locaStringBuilder.toString().replaceAll("\\[sender\\]", callerName);
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
Dan D.
  • 32,246
  • 5
  • 63
  • 79