java 使用正则表达式从字符串中删除方括号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15083621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove square brackets from a String using Regular Expressions?
提问by austindg
How would I remove all square brackets ("[]") from a given String in Java?
如何从 Java 中的给定字符串中删除所有方括号(“[]”)?
String s = "[abcdefg]";
s = s.replaceAll(regex, "");
What regular expression would be used in this case?
在这种情况下将使用什么正则表达式?
回答by Ivaylo Strandjev
Use this one:
使用这个:
String s = "[abcdefg]";
String regex = "\[|\]";
s = s.replaceAll(regex, "");
System.out.println(s);
回答by radai
you could match it using something like "\\[([^\\]])\\]"
(opening brachet, a sequence of anything that isnt a closing bracket (encased inside ()
for later reference), followed by a closing bracket) and then replace the whole match (group 0) with the contents matched inside the ()
block (group 1)
你可以使用类似的东西来匹配它"\\[([^\\]])\\]"
(打开括号,任何不是右括号的序列(包含在里面()
供以后参考),然后是一个右括号),然后用里面匹配的内容替换整个匹配(组 0)()
块(组 1)