我想使用java删除字符串中所有类型的括号字符(例如:[],(),{})。
我尝试使用此代码:
String test = "watching tv (at home)";
test = test.replaceAll("(","");
test = test.replaceAll(")","");
但它没有用,请帮帮我。
答案 0 :(得分:21)
replaceAll
的第一个参数采用正则表达式。
所有括号在正则表达式中都有意义:正则表达式中使用括号来引用capturing groups, 方括号用于character class&大括号用于匹配的字符出现。 因此,它们都需要被转义...但是这里的字符可以简单地用character class括起来,只需要方括号的转义
test = test.replaceAll("[\\[\\](){}]","");
答案 1 :(得分:17)
删除包含所有括号,大括号和方括号的所有标点符号...根据问题:
String test = "watching tv (at home)";
test = test.replaceAll("\\p{P}","");
答案 2 :(得分:4)
传递给replaceAll()
方法的第一个参数应该是正则表达式。如果您想匹配这些文字括号字符,则需要将\\(
,\\)
转义为它们。
您可以使用以下方法删除括号字符。 Unicode property \p{Ps}
将匹配任何类型的左括号,Unicode property \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"
答案 3 :(得分:2)
您需要转义括号,因为它将被视为正则表达式的一部分
String test = "watching tv (at home)";
test = test.replaceAll("\\(","");
test = test.replaceAll("\\)","");
同样要删除所有括号,请尝试
String test = "watching tv (at home)";
test = test.replaceAll("[\\(\\)\\[\\]\\{\\}]","");
答案 4 :(得分:2)
您可以使用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
答案 5 :(得分:0)
subject = StringUtils.substringBetween(subject," [","]")
答案 6 :(得分:0)
字符串列表='[{121223123123123123}]';
String accountlist = list.replaceAll(“ [\ [\]]”,“”);
在这种情况下,我要从字符串中删除[]。
输出:字符串列表='{121223123123123123}';