如何替换 java 中的“{Name}”

How to replace '{Name}' in java

我需要用值替换 {Name} 等字符串中的值。
我们如何替换特殊字符{}
我试过这个:

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

但是如果我们有特殊字符,这就不起作用了。

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

碰巧{}在正则表达式语法中有特殊含义,因此需要转义。尝试使用 str.replaceAll("\{Name\}","A");

前面的额外 \ 指示正则表达式引擎将 {} 作为实际字符(没有特殊含义)进行威胁。由于这是 Java,您还需要转义 \ 字符,这就是为什么您需要其中两个字符的原因。

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

示例:(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);

输出:

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