Java String ReplaceAll method giving illegal repetition error?

Johnydep picture Johnydep · Dec 13, 2011 · Viewed 23.2k times · Source

I have a string and when I try to run the replaceAll method, I am getting this strange error:

String str = "something { } , op";
str = str.replaceAll("o", "\n"); // it works fine
str = str.replaceAll("{", "\n"); // does not work

and i get a strange error:

Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal repetition {  

How can I replace the occurrences of "{" ?

Answer

codaddict picture codaddict · Dec 13, 2011

A { is a regex meta-character used for range repetitions as {min,max}. To match a literal { you need to escape it by preceding it with a \\:

str = str.replaceAll("\\{", "\n"); // does work