如何在java中替换"{Name}"

Akh*_*ila 5 java special-characters

我需要用值替换字符串中的{Name}值.
我们怎样才能更换特殊字符{}
我试过这个:

str.replaceAll("{Name}","A");
Run Code Online (Sandbox Code Playgroud)

但如果我们有特殊字符,这不起作用.

T.J*_*der 14

使用replace而不是replaceAll,因为replace不期望和解析正则表达式.

示例:( 实时复印件)

String str = "Here it is: {Name} And again: {Name}";
System.out.println("Before: " + str);
str = str.replace("{Name}","A");
System.out.println("After: " + str);
Run Code Online (Sandbox Code Playgroud)

输出:

Before: Here it is: {Name} And again: {Name}
After: Here it is: A And again: A


npi*_*nti 12

根据JavaDoc,该.replaceAll(String regex, String replacement)方法将正则表达式作为第一个参数.

它恰好发生在正则表达式语法中{}具有特殊含义,因此需要进行转义.尝试使用str.replaceAll("\\{Name\\}","A");.

额外\的前面指示正则表达式引擎威胁{}作为实际角色(没有它们的特殊含义).由于这是Java,你还需要转义\字符,这就是你需要两个字符的原因.