How to remove brackets character in string (java)

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

I tried using this code:

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

But it does not work, please help me.

+7
java string regex brackets
source share
6 answers

To remove all punctuation marks that include all brackets, curly braces and square brackets ... according to the question:

 String test = "watching tv (at home)"; test = test.replaceAll("\\p{P}",""); 
+11
source share

The first argument to replaceAll takes a regular expression.

All brackets make sense in regex: brackets are used in regex to refer to capture groups , square brackets are used for the character class , and curly braces are used to match characters. Therefore, all of them must be escaped ... However, here the characters can simply be enclosed in a character class with the simple escaping required for square brackets

 test = test.replaceAll("[\\[\\](){}]",""); 
+18
source share

The first argument passed to replaceAll() must be a regular expression. If you want to combine these alphabetic characters, you need to output \\( , \\) them.

You can use the following to remove parenthesis characters. The Unicode \p{Ps} property will match any opening bracket, and the Unicode \p{Pe} property will match any closing bracket.

 String test = "watching tv (at home) or [at school] or {at work}()[]{}"; test = test.replaceAll("[\\p{Ps}\\p{Pe}]", ""); System.out.println(test); //=> "watching tv at home or at school or at work" 
+4
source share

You need to get out of the bracket, as it will be considered as part of the regular expression

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

Also, to remove all brackets, try

 String test = "watching tv (at home)"; test = test.replaceAll("[\\(\\)\\[\\]\\{\\}]",""); 
+2
source share

You can use String.replace instead of String.replaceAll for better performance , as it searches for the exact sequence and does not need regular expressions.

 String test = "watching tv (at home)"; test = test.replace("(", " "); test = test.replace(")", " "); test = test.replace("[", " "); test = test.replace("]", " "); test = test.replace("{", " "); test = test.replace("}", " "); 

If you work with texts, I recommend that you replace the brackets with blank space to avoid combining words: watching tv(at home) -> watching tvat home

+2
source share

subject = StringUtils.substringBetween (subject, "[", "]")

0
source share

All Articles