Reputation: 14103
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
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
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
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
Reputation: 26930
In java:
String resultString = subjectString.replaceAll("[\\[\\]\"]", "");
this will replace []"
with nothing.
Upvotes: 0
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