how to remove brackets character in string (java)

久未见 提交于 2019-11-29 03:59:59

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}","");

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("[\\[\\](){}]","");

The first argument passed to the replaceAll() method should be a regular expression. If you want to match those literal bracket characters you need to escape \\(, \\) them.

You could use the following to remove bracket characters. Unicode property \p{Ps} will match any kind of opening bracket and Unicode property \p{Pe} matches any kind of 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"

You need to escape the bracket as it will be treated as part of a regex

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("[\\(\\)\\[\\]\\{\\}]","");

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 are working with texts I recommend you to replace the brackets with an empty space to avoid words joining together: watching tv(at home) -> watching tvat home

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!