简体   繁体   English

如何去除特殊字符String开头和结尾的方括号?

[英]How to remove the square brackets at the beginning and end of the special characters String?

Below is the example where I want to remove the square brackets using Java:-下面是我想使用 Java 删除方括号的示例:-

String specialCharacters = "[!& *=~}[]"
String specialCharactes1 = "[[[&%*@#(#][[]"

I want the result like this respectively:-我分别想要这样的结果:-

!& *=~}[ !& *=~}[

[[&%*@#(#][[ [[&%*@#(#][[

That Means I want to remove only one square brackets from both the ends.这意味着我只想从两端删除一个方括号。 I saw many solutions but those were related to JavaScript.我看到了很多解决方案,但这些都与 JavaScript 有关。

This can be done using regex but I am not sure How I can replicate this.这可以使用正则表达式来完成,但我不确定如何复制它。

Thanks @Elliott Frisch for the solution.感谢@Elliott Frisch 的解决方案。 This was just a silly mistake of inverted commas.这只是引号的愚蠢错误。 Your solution worked.你的解决方案奏效了。

System.out.println(specialCharacters.replaceAll("\\[(.+)\\]", "$1"));
System.out.println(specialCharactes1.replaceAll("\\[(.+)\\]", "$1"));
String specialCharacters = "[!& *=~}[]";
if(null!=specialCharacters)
{
   String answer = specialCharacters.substring(specialCharacters.indexOf(" 
                    [")+1,specialCharacters.indexOf("]"));
}

This will work if there is only one [ and ] in the input string如果输入字符串中只有一个 [ 和 ],这将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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