Petar Toshev
Petar Toshev

Reputation: 67

How to remove [] and () from java string

I want to remove [, ], ( and ) from my java String. I have tried .replaceAll("(", ""); and .replaceAll("[", ""); but it didn't work. In my program str is read from a file.

String str = "I [need] this ]message () without (this[])";

Upvotes: 1

Views: 15553

Answers (3)

Gordon MacDonald
Gordon MacDonald

Reputation: 156

You need to add a double backslash before the [ and the ( in your replaceAll statements:

str = str.replaceAll("\\[", "").replaceAll("\\(", "").replaceAll("\\]", "").replaceAll("\\)", "");

(FYI a single \ will not work as it will evaluate ) as an escaped special character,)

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201477

You need to escape the (, ), [ and ]. You can do that with \\. Something like,

String str = "I [need] this ]message () without (this[])";
str = str.replaceAll("[\\[\\]\\(\\)]", "");
System.out.println(str);

Output is

I need this message  without this

Upvotes: 5

exception1
exception1

Reputation: 1249

You probably had the solution, but the replaceAllmethod does not modify the string. Save the result in a variable:

String str = "I [need] this ]message () without (this[])".replaceAll("[()\\[\\]]", "");

The argument "[()\\[\\]]" is a regex. The outer [] means: one of the inner symbols. These are ( and ). Additionally, you want to match [ and ]. But you have to put \\ before them because they have that special meaning ("one of").

Upvotes: 7

Related Questions