2

I have this code :

    buffer = buffer.replaceAll("(","");

That is returning java.util.regex.PatternSyntaxException I don't know why. Help, please.

Khalil Hamani
  • 71
  • 2
  • 3
  • 13
  • 2
    Do you know why you use `replaceAll` instead of `replace`? – Tom May 18 '16 at 12:08
  • 4
    because ``(`` is a special character .. also see this http://stackoverflow.com/questions/11715863/replace-all-method-throws-patternsyntaxexception – rev_dihazum May 18 '16 at 12:09
  • @Tom yes because I need to delete all occurences of "(" in this String. – Khalil Hamani May 18 '16 at 12:11
  • @rev_dihazum what should I do then ? – Khalil Hamani May 18 '16 at 12:12
  • 2
    *"yes because I need to delete all occurences of "(" in this String."* So you haven't even thought about reading the JavaDoc? Well, this is the perfect time to do it now. And then rethink if `replaceAll` is really the method you want to use. And _yes_ that "all" in `replaceAll` is misleading. – Tom May 18 '16 at 12:14
  • 2
    Java's naming is terrible here. `replace` should have been called `replaceAll` and that in turn `replaceAllOccurencesOfRegex` or whatever. Because that's what those methods actually do. – zapl May 18 '16 at 12:18

1 Answers1

1

Replace replaceAll("(","") with replaceAll("\\(", ""). ( is a special character, you should paste \\ before each of \.[]{}()*+-?^$|.

"sta(c(k(overfl(ow".replaceAll("\\(", "") -> "stackoverflow"

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • You should replace the answer with close vote as duplicate ... – Tom May 18 '16 at 12:18
  • @Tom, I've voted to close – Andrew Tobilko May 18 '16 at 12:19
  • This is good, but then don't answer it, as well. This is discouraged and can attract downvotes. Closing as duplicate exist to avoid "spreading" knowledge about a specific fact all other the place, which makes it harder to maintain it. – Tom May 18 '16 at 12:20