3

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}

5
  • 1
    replaceAll's first parameter must be regex, it's not treated as string or char. Commented Aug 27, 2015 at 8:11
  • how does this compiles? Commented Aug 27, 2015 at 8:12
  • @Lrrr there is no issue in compilation I faced. Commented Aug 27, 2015 at 8:13
  • please, post your expected output... Commented Aug 27, 2015 at 8:14
  • 2
    try s.replaceAll("\\{", "\\\\{") Commented Aug 27, 2015 at 8:17

2 Answers 2

7

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}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Should work.

1 Comment

@JordiCastilla the post has been modified after I answered the question. If we need the output after modification it would lokk like as follows: System.out.println(s.replaceAll("\\{", "\\\\{"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.