Reputation: 63
How would I remove all square brackets ("[]") from a given String in Java?
String s = "[abcdefg]";
s = s.replaceAll(regex, "");
What regular expression would be used in this case?
Upvotes: 3
Views: 19433
Reputation: 70929
Use this one:
String s = "[abcdefg]";
String regex = "\\[|\\]";
s = s.replaceAll(regex, "");
System.out.println(s);
Upvotes: 11
Reputation: 24192
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)
Upvotes: 2