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 .

1

2 Answers 2

5

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

System.out.println(data.replaceAll("[{}\\[\\]]", " "));
Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
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.
2

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

System.out.println(data.replaceAll("[{}\\[\\]]", " "));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.