Reputation: 61
I need to replace a value in a string like {Name}
with values.
How can we replace the special character {
and }
?
I have tried this:
str.replaceAll("{Name}","A");
But this doesnt work if we have special characters.
Upvotes: 5
Views: 2333
Reputation: 1074565
Use replace
rather than replaceAll
, since replace
doesn't expect and parse a regular expression.
Example: (live copy)
String str = "Here it is: {Name} And again: {Name}";
System.out.println("Before: " + str);
str = str.replace("{Name}","A");
System.out.println("After: " + str);
Output:
Before: Here it is: {Name} And again: {Name} After: Here it is: A And again: A
Upvotes: 14
Reputation: 52185
As per the JavaDoc, the .replaceAll(String regex, String replacement)
method takes in a regular expression as the first parameter.
It so happens that {
and }
have special meaning in regular expression syntax and thus need to be escaped. Try using str.replaceAll("\\{Name\\}","A");
.
The extra \
in front instructs the regular expression engine to threat the {
and }
as actual characters (without their special meaning). Since this is Java, you need to also escape the \
character which is why you need two of them.
Upvotes: 12