我有一个字符串而且我想替换{to\{...当我使用replace方法然后它可以工作但是当我使用replaceAll时它会给出错误,例如Illegal repetition
是什么原因?
String s = "One{ two } three {{{ four}";
System.out.println(s.replace("{", "\\{"));
System.out.println(s.replaceAll("{", "\\{"));
Run Code Online (Sandbox Code Playgroud)
预期输出为 - 一个\ {两个}三个\ {\ {\ {{四个}
正如所解释的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("\\{", "\\\\{"));
Run Code Online (Sandbox Code Playgroud)
输出:
One{ two } three {{{ four}
One\{ two } three \{\{\{ four}
One\{ two } three \{\{\{ four}
Run Code Online (Sandbox Code Playgroud)