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.
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.
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 ( ).
You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String.
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("[\\[\\](){}]","");
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}","");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With