Java不能用replaceAll方法替换"{"

-2 java string methods replaceall

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

试过:

"some { string".replaceAll("{", "other string");
Run Code Online (Sandbox Code Playgroud)

错误如下:

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

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

svd*_*ter 7

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

尝试使用replace方法而不是replaceAll

"some { string".replace("{", "other string");
Run Code Online (Sandbox Code Playgroud)

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

"some { string".replaceAll("\\{", "other string");
Run Code Online (Sandbox Code Playgroud)


Nav*_*hna 5

试试replace()这样

"some { string".replace("{", "other string");
Run Code Online (Sandbox Code Playgroud)

或使用replaceAll以下正则表达式格式

"some { string".replaceAll("\\{", "your string to replace");
Run Code Online (Sandbox Code Playgroud)

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

  • `replace` 替换所有出现,而不仅仅是第一个。见 https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence) @Korashen @Navneet Krishna (3认同)

归档时间:

查看次数:

853 次

最近记录:

7 年,4 月 前