chutsu
chutsu

Reputation: 14103

How do I replace all "[", "]" and double quotes in Java

I'm am having difficulty using the replaceAll method to replace square brackets and double quotes. Any ideas?

Edit:

So far I've tried:

replace("\[", "some_thing") // returns illegal escape character
replace("[[", "some_thing") // returns Unclosed character class
replace("^[", "some_thing") // returns Unclosed character class

Upvotes: 3

Views: 16699

Answers (5)

James Bassett
James Bassett

Reputation: 9908

Alternatively, if you wished to replace ", [ and ] with different characters (instead of replacing all with empty String) you could use the replaceEachRepeatedly() method in the StringUtils class from Commons Lang.

For example,

String input = "abc\"de[fg]hi\"";
String replaced = StringUtils.replaceEachRepeatedly(input, 
    new String[]{"[","]","\""}, 
    new String[]{"<open_bracket>","<close_bracket>","<double_quote>"});
System.out.println(replaced);

Prints the following:

abc<double_quote>de<open_bracket>fg<close_bracket>hi<double_quote>

Upvotes: 0

ziesemer
ziesemer

Reputation: 28697

The replaceAll method is operating against Regular Expressions. You're probably just wanting to use the "replace" method, which despite its name, does replace all occurrences.

Looking at your edit, you probably want:

someString
.replace("[", "replacement")
.replace("]", "replacement")
.replace("\"", "replacement")

or, use an appropriate regular expression, the approach I'd actually recommend if you're willing to learn regular expressions (see Mark Peter's answer for a working example).

Upvotes: 3

Mark Peters
Mark Peters

Reputation: 81104

Don't use replaceAll, use replace. The former uses regular expressions, and [] are special characters within a regex.

String replaced = input.replace("]", ""); //etc

The double quote is special in Java so you need to escape it with a single backslash ("\"").

If you want to use a regex you need to escape those characters and put them in a character class. A character class is surrounded by [] and escaping a character is done by preceding it with a backslash \. However, because a backslash is also special in Java, it also needs to be escaped, and so to give the regex engine a backslash you have to use two backslashes (\\[).

In the end it should look like this (if you were to use regex):

String replaced = input.replaceAll("[\\[\\]\"]", "");

Upvotes: 7

FailedDev
FailedDev

Reputation: 26930

In java:

String resultString = subjectString.replaceAll("[\\[\\]\"]", "");

this will replace []" with nothing.

Upvotes: 0

tskuzzy
tskuzzy

Reputation: 36476

replaceAll() takes a regex so you have to escape special characters. If you don't want all the fancy regex, use replace().

String s = "[h\"i]";
System.out.println( s.replace("[","").replace("]","").replace("\"","") );

With double quotes, you have to escape them like so: "\""

Upvotes: 1

Related Questions