27

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 "{" ?

codaddict
  • 445,704
  • 82
  • 492
  • 529
Johnydep
  • 6,027
  • 20
  • 57
  • 74

3 Answers3

43

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
codaddict
  • 445,704
  • 82
  • 492
  • 529
20

If you really intend to replace single characters and not regexes (which is what you seem to want to do here), you should use .replace(), not .replaceAll(). In spite of its name, .replace() will replace ALL occurrences, not just the first one.

And in case you wonder, String implements CharSequence, so .replace("{", "\n") will work.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
fge
  • 119,121
  • 33
  • 254
  • 329
  • Holy crap... I've been using Groovy for years and always assumed `replace()` just replaced the first instance. That's what I get for not looking at the docs! – Daniel Black Dec 02 '21 at 21:44
6

Escape it:

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

This is needed since the first argument to replaceAll() is a regular expression, and { has a special meaning in Java regular expressions (it's a repetition operator, hence the error message).

NPE
  • 486,780
  • 108
  • 951
  • 1,012