Reputation: 3963
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
Reputation: 32391
This works:
locaStringBuilder.toString().replaceAll("\\[sender\\]", callerName);
Upvotes: 0
Reputation: 3095
Use this
localStringBuilder.toString().replaceAll("\\[sender\\]", callerName);
Upvotes: 0
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
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