Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove brackets character in string (java)

I want to remove all type of brackets character (example: [],(),{}) in string by using java.

I tried using this code:

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

But it's not working, help me please.

like image 749
Muhammad Haryadi Futra Avatar asked Sep 15 '14 16:09

Muhammad Haryadi Futra


People also ask

How do you remove brackets from a string?

There are two ways in which you can remove the parentheses from a String in Java. You can traverse the whole string and append the characters other than parentheses to the new String. You can use the replaceAll() method of the String class to remove all the occurrences of parentheses.

How do you remove curly braces from string in Java?

If one needs to use the replace() function to replace any open curly brackets "{" contained within a String with another character, you need to first escape with a backslash "\". This syntax not only applies to curly brackets { }, but also with "square brackets" [ ] and parentheses ( ).

How do you remove unwanted characters from a string in Java?

You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String.


2 Answers

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("[\\[\\](){}]","");
like image 199
Reimeus Avatar answered Sep 19 '22 13:09

Reimeus


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}","");
like image 34
StackFlowed Avatar answered Sep 18 '22 13:09

StackFlowed