[英]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
. 我想从
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
我该怎么做才能从
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 . [
和]
是regex中的特殊元字符,表示字符类的开始和结束。 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("]", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.