Reputation: 2272
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
Upvotes: 2
Views: 1047
Reputation: 174776
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
Upvotes: 6
Reputation: 1892
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("]", "");
Upvotes: 0