Java 不能将"{"替换为 replaceAll 方法



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

尝试:

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

错误如下:

java.util.regex.PatternSyntaxException:发生非法重复

欢迎任何想法!也许有变通办法?!

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

尝试使用replace方法而不是replaceAll

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

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

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

尝试使用类似的replace()

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

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

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

注意:在replace()的情况下,第一个参数是字符序列,但在replaceAll的情况下第一个参数为regex

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

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

您需要转义字符"{".

试试这个:

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

{是正则表达式引擎的一个指示符,表示您将启动重复指示符,如{2,4},意思是"前一个令牌的2到4倍"。

但是{f是非法的,因为它后面必须跟一个数字,所以它抛出一个异常。

你可以做一些类似的事情

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

您必须使用转义符\:

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

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

  1. 替换:"xxx".替换("{","xxx"(
  2. replaceAll:"xxx".replace("\{","xxx"(

String replace((和replaceAll((之间的差异

最新更新