Java replace all square brackets in a string
Solution 1:
The replaceAll method is attempting to match the String literal []
which does not exist within the String
try replacing these items separately.
String str = "[Chrissman-@1]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");
Solution 2:
Your regex matches (and removes) only subsequent square brackets. Use this instead:
str = str.replaceAll("\\[|\\]", "");
If you only want to replace bracket pairs with content in between, you could use this:
str = str.replaceAll("\\[(.*?)\\]", "$1");
Solution 3:
You're currently trying to remove the exact string []
- two square brackets with nothing between them. Instead, you want to remove all [
and separately remove all ]
.
Personally I would avoid using replaceAll
here as it introduces more confusion due to the regex part - I'd use:
String replaced = original.replace("[", "").replace("]", "");
Only use the methods which take regular expressions if you really want to do full pattern matching. When you just want to replace all occurrences of a fixed string, replace
is simpler to read and understand.
(There are alternative approaches which use the regular expression form and really match patterns, but I think the above code is significantly simpler.)