简体   繁体   中英

Replace All `[ ]` character from the string

I have a String.

 String myStrangeString = "java-1.7, ant-1.6.5, sonar-runner], [java-1.7, ant-1.6.5, sonar-runner], [java-1.7, ant-1.6.5, sonar-runner";

I want to remove all the [] characters from the myStrangeString .

I tried,

myStrangeString.replaceAll("[[]]", "")

but got error as

Return Value :Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 3
[[]]
   ^
    at java.util.regex.Pattern.error(Pattern.java:1924)
    at java.util.regex.Pattern.clazz(Pattern.java:2493)
    at java.util.regex.Pattern.sequence(Pattern.java:2030)
    at java.util.regex.Pattern.expr(Pattern.java:1964)
    at java.util.regex.Pattern.compile(Pattern.java:1665)
    at java.util.regex.Pattern.<init>(Pattern.java:1337)
    at java.util.regex.Pattern.compile(Pattern.java:1022)
    at java.lang.String.replaceAll(String.java:2162)
    at Test.main(Test.java:8)

what can i do to remove the [] from my myStrangeString

You need to escape those inner brackets. [ and ] are special meta characters in regex which means the start and end of a character class . So to match a literal [ , ] symbols, you must need to escape that.

myStrangeString.replaceAll("[\\[\\]]", "")

Example:

String myStrangeString = "java-1.7, ant-1.6.5, sonar-runner], [java-1.7, ant-1.6.5, sonar-runner], [java-1.7, ant-1.6.5, sonar-runner";
System.out.println(myStrangeString.replaceAll("[\\[\\]]", ""));

Output:

java-1.7, ant-1.6.5, sonar-runner, java-1.7, ant-1.6.5, sonar-runner, java-1.7, ant-1.6.5, sonar-runner

i think is the answer you are looking for is

myStrangeString.replaceAll("[\\[\\]]", "");

but if your string is not big and performance is not an issue you can do it in two steps... remove all [ and then remove all ]

 myStrangeString.replace("[", "");
 myStrangeString.replace("]", "");

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