关于字符串:Java无法用replaceAll方法替换“ {”

Java can't replace “{” with replaceAll method

本问题已经有最佳答案,请猛点这里访问。

我们正在使用String的replaceAll方法,并且不能在任何字符串中替换{。
我们的例子:

尝试过:

1
"some { string".replaceAll("{","other string");

错误如下:

java.util.regex.PatternSyntaxException: Illegal repetition occurs

开放任何想法! 也许有解决方法?!


使用replaceAll需要一个正则表达式(regex)

尝试使用replace方法而不是replaceAll

1
"some { string".replace("{","other string");

或使用\\\\在正则表达式中转义特殊字符

1
"some { string".replaceAll("\\\\{","other string");

像这样尝试replace()

1
"some { string".replace("{","other string");

或将replaceAll与以下正则表达式格式一起使用

1
"some { string".replaceAll("\\\\{","your string to replace");

注意:对于replace(),第一个参数是字符序列,但是对于replaceAll,第一个参数是regex


您需要转义{,因为它在regex中具有特殊含义。用 :

1
String s ="some { string".replaceAll("\\\\{","other string");

{是正则表达式引擎的指示符,您即将开始一个重复指示符,例如{2,4},表示"是先前标记的2到4倍"。

但是{f是非法的,因为必须在其后跟数字,所以它引发异常。

你可以做这样的事情

1
"some { string".replaceAll("\\\\{","other string");

您需要转义字符" {"。

试试这个 :

1
"some { string".replaceAll("\\\\{","other string");

您必须使用转义字符\\\\

1
"some { string".replaceAll("\\\\{","other string");

字符{在正则表达式中保留,这就是为什么必须转义以匹配文字的原因。或者,可以使用replace仅考虑CharSequence,而不考虑正则表达式。


  • 更换:
    " xxx" .replace(" {"," xxx")
  • 全部替换:
    " xxx" .replace(" \ {"," xxx")
  • 字符串replace()和replaceAll()之间的区别