简体   繁体   English

如何从Java字符串中删除[]和()

[英]How to remove [] and () from java string

I want to remove [, ], ( and ) from my java String. 我想从我的Java字符串中删除[,],(和)。 I have tried .replaceAll("(", ""); and .replaceAll("[", ""); but it didn't work. In my program str is read from a file. 我已经尝试过.replaceAll("(", "");.replaceAll("[", "");但是没有用,在我的程序中str是从文件中读取的。

String str = "I [need] this ]message () without (this[])";

You probably had the solution, but the replaceAll method does not modify the string. 您可能有解决方案,但是replaceAll方法不会修改字符串。 Save the result in a variable: 将结果保存在变量中:

String str = "I [need] this ]message () without (this[])".replaceAll("[()\\[\\]]", "");

The argument "[()\\\\[\\\\]]" is a regex. 参数"[()\\\\[\\\\]]"是一个正则表达式。 The outer [] means: one of the inner symbols. 外部[]表示:内部符号之一。 These are ( and ) . 这些是() Additionally, you want to match [ and ] . 另外,您要匹配[] But you have to put \\\\ before them because they have that special meaning ("one of"). 但是您必须在它们前面加上\\\\ ,因为它们具有特殊含义(“其中之一”)。

You need to escape the ( , ) , [ and ] . 您需要转义()[] You can do that with \\\\ . 您可以使用\\\\做到这一点。 Something like, 就像是,

String str = "I [need] this ]message () without (this[])";
str = str.replaceAll("[\\[\\]\\(\\)]", "");
System.out.println(str);

Output is 输出是

I need this message  without this

You need to add a double backslash before the [ and the ( in your replaceAll statements: 您需要在replaceAll语句中的[和()之前添加双反斜杠:

str = str.replaceAll("\\[", "").replaceAll("\\(", "").replaceAll("\\]", "").replaceAll("\\)", "");

(FYI a single \\ will not work as it will evaluate ) as an escaped special character,) (仅供参考,单个\\不会起作用,因为它将评估)作为转义的特殊字符,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM