REMOVE BRACKETS CHARACTER IN JAVA STRING

Nigel Bunyan

Total Post:20

Points:140
Posted by  Nigel Bunyan
Java  String 
 730  View(s)
Ratings:
Rate this:
I want to remove all type of brackets character (example: [],(),{}) in string by using java.

I am doing it like this :

String test = "watching tv (at home)"; 
test = test.replaceAll("(","");
test = test.replaceAll(")","");

But its not working . Suggest me a solution please. 
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Remove brackets character in java string

    To remove all punctuation marks that include all brackets, braces and sq. brackets ... as per the question is:

    String test = "watching tv (at home)"; 
    test = test.replaceAll("\\p{P}","");
    But this solution removes also symbols like ., ,, ;, etc

    The first argument of replaceAll takes a regular expression.

    All the brackets have meaning in regex: Brackets are used in regex to reference capturing groups, square brackets are used for character class & braces are used for matched character occurrence. Therefore they all need to be escaped...However here the characters can simply be enclosed in a character class with just escaping required for square brackets

    test = test.replaceAll("[\\[\\](){}]","");

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!