java字符串替换方法有效,但使用replaceAll引发错误
我有一个字符串,我想替换{to\{…当我使用replace方法时,它会工作,但当我使用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
非法重复
原因是什么
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(“\\{,”\\\{”);