austindg
austindg

Reputation: 63

Remove square brackets from a String using Regular Expressions?

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

Answers (2)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

Use this one:

 String s = "[abcdefg]";
 String regex = "\\[|\\]";
 s = s.replaceAll(regex, "");
 System.out.println(s);

Upvotes: 11

radai
radai

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

Related Questions