How to replace '{Name}' in java

I need to replace the value in a string like {Name} with values.
How can we replace the special character { and } ?
I tried this:

 str.replaceAll("{Name}","A"); 

But this does not work if we have special characters.

+5
source share
2 answers

According to JavaDoc, the .replaceAll(String regex, String replacement) method accepts a regular expression as the first parameter.

It so happened that { and } have special meaning in the syntax of regular expressions and, therefore, must be escaped. Try using str.replaceAll("\\{Name\\}","A"); .

An optional \ in front instructs the regex engine to threaten { and } as valid characters (without their special meaning). Since this is Java, you also need to escape the \ character, so you need two of them.

+12
source

Use replace , not replaceAll , since replace does not expect or 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
+14
source

Source: https://habr.com/ru/post/1232167/


All Articles