Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java字符串替换方法有效,但使用replaceAll引发错误_Java_String - Fatal编程技术网

java字符串替换方法有效,但使用replaceAll引发错误

java字符串替换方法有效,但使用replaceAll引发错误,java,string,Java,String,我有一个字符串,我想替换{to\{…当我使用replace方法时,它会工作,但当我使用replaceAll时,它会给出错误,比如非法重复 原因是什么 String s = "One{ two } three {{{ four}"; System.out.println(s.replace("{", "\\{")); System.out.println(s.replaceAll("{", "\\{")); 预期的输出是-1\{2}3\{{4}String replaceAll预期的是regex

我有一个字符串,我想替换{to\{…当我使用replace方法时,它会工作,但当我使用replaceAll时,它会给出错误,比如
非法重复
原因是什么

String s = "One{ two } three {{{ four}";
System.out.println(s.replace("{", "\\{"));
System.out.println(s.replaceAll("{", "\\{"));

预期的输出是-1\{2}3\{{4}

String replaceAll预期的是regex,而replace预期的是charSequence。因此修改了代码

System.out.println(s.replaceAll("\\{", "\\{"));

应该起作用。

正如所解释的
String::replaceAll
需要
regex
Strinng::replace
需要
charSequence
。因此,必须同时转义
\
{
,才能按预期匹配

String s = "One{ two } three {{{ four}";

System.out.println(s);
System.out.println(s.replace("{", "\\{"));
System.out.println(s.replaceAll("\\{", "\\\\{"));
输出:

One{ two } three {{{ four}
One\{ two } three \{\{\{ four}
One\{ two } three \{\{\{ four}

replaceAll的第一个参数必须是regex,它不被视为字符串或字符。这是如何编译的?@Lrrr我遇到的编译没有问题。请发布您的预期输出…尝试
s.replaceAll(“\\{”,“\\\{”)
@JordiCastilla在我回答问题后,帖子已经被修改。如果修改后我们需要输出,它将如下所示:System.out.println(s.replaceAll(“\\{,”\\\{”);