简体   繁体   中英

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

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("[\\[\\]\"]", "");

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).

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: "\\""

In java:

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

this will replace []" with nothing.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM