0

I am learning java and I want to replace all [] and {} with a space using java RegExp.

What i'm tried,

final String data = "{a:b,c:d,e:[f,g,h]}";
System.out.println(data.replaceAll("[{}[]]", " ")); 

but am getting java.util.regex.PatternSyntaxException: Unclosed character class near index 5 [{}[]]. ^

I think the java thinks that the ] at 5th position as the ending point of the RegExp.

So how can i escape that square bracket and replace all []{} with a space .

theapache64
  • 9,428
  • 7
  • 57
  • 87

2 Answers2

5

You must escape [, ] present inside [] (character class)

System.out.println(data.replaceAll("[{}\\[\\]]", " "));
Avinash Raj
  • 166,785
  • 24
  • 204
  • 249
  • So the double slash is used to escape syntax char in regex ? or it can be used with any string? i think commonly we use `\` single slash to escape a char from a string. isn't ? – theapache64 Aug 03 '15 at 17:12
  • Ya, I other lang which use `/` as delimiter uses only single slash. But in case of `"` , you need to escape backslash one more time. Or otherwise it would be readed as an escape sequence. – Avinash Raj Aug 03 '15 at 17:14
2

You need to escape the special characters [ and ] with backslashes:

System.out.println(data.replaceAll("[{}\\[\\]]", " "));
M A
  • 69,673
  • 13
  • 131
  • 165