Naveen Ramawat
Naveen Ramawat

Reputation: 1445

java String replace method works but throwing error with replaceAll

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

Answers (2)

Jordi Castilla
Jordi Castilla

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

Rahul Yadav
Rahul Yadav

Reputation: 1513

String replaceAll expects regex whereas replace expects charSequence. Hence modifying the code

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

Should work.

Upvotes: 2

Related Questions