Reputation: 1445
I have a string andn I want to replace { to \{ ... When I use replace method then it works but when I use replaceAll then it is giving error like Illegal repetition
What is the reason?
String s = "One{ two } three {{{ four}";
System.out.println(s.replace("{", "\\{"));
System.out.println(s.replaceAll("{", "\\{"));
Expected output is - One\{ two } three \{\{\{ four}
Upvotes: 3
Views: 1469
Reputation: 26961
As explained String::replaceAll
expects regex
and Strinng::replace
expects charSequence
. So you must escape both \
and {
in order to match as you expect.
String s = "One{ two } three {{{ four}";
System.out.println(s);
System.out.println(s.replace("{", "\\{"));
System.out.println(s.replaceAll("\\{", "\\\\{"));
Output:
One{ two } three {{{ four}
One\{ two } three \{\{\{ four}
One\{ two } three \{\{\{ four}
Upvotes: 7
Reputation: 1513
String replaceAll expects regex whereas replace expects charSequence. Hence modifying the code
System.out.println(s.replaceAll("\\{", "\\{"));
Should work.
Upvotes: 2