如何删除字符串中的括号字符(java)

我想通过使用java删除字符串中所有类型的括号字符(例如:[],(),{})。

我尝试使用此代码:

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

但它没有用,请帮帮我。

删除包含所有括号,大括号和sq括号的所有标点符号…根据问题是:

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

replaceAll的第一个参数采用正则表达式。

所有括号在正则表达式中都有意义:括号在正则表达式中用于引用捕获组 ,方括号用于字符类 ,括号用于匹配的字符出现。 因此它们都需要被转义…但是这里的字符可以简单地包含在一个字符类中 ,只需要方括号转义

 test = test.replaceAll("[\\[\\](){}]",""); 

传递给replaceAll()方法的第一个参数应该是正则表达式。 如果要匹配那些文字括号字符,则需要转义\\(\\)它们。

您可以使用以下内容删除括号字符。 Unicode属性\p{Ps}将匹配任何类型的左括号和Unicode属性\p{Pe}匹配任何类型的右括号。

 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" 

您需要转义括号,因为它将被视为正则表达式的一部分

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

还要删除所有括号尝试

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

您可以使用String.replace而不是String.replaceAll来获得更好的性能 ,因为它会搜索确切的序列并且不需要正则表达式。

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

如果你正在使用文本我建议你用空格替换括号,以避免单词连接在一起: watching tv(at home) -> watching tvat home

subject = StringUtils.substringBetween(subject,“[”,“]”)