问题
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.
回答1:
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}","");
回答2:
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("[\\[\\](){}]","");
回答3:
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"
回答4:
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("[\\(\\)\\[\\]\\{\\}]","");
回答5:
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
回答6:
subject =StringUtils.substringBetween(subject, "[", "]")
来源:https://stackoverflow.com/questions/25852961/how-to-remove-brackets-character-in-string-java