簡體   English   中英

如何從Java字符串中刪除[]和()

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

我想從我的Java字符串中刪除[,],(和)。 我已經嘗試過.replaceAll("(", "");.replaceAll("[", "");但是沒有用,在我的程序中str是從文件中讀取的。

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

您可能有解決方案,但是replaceAll方法不會修改字符串。 將結果保存在變量中:

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

參數"[()\\\\[\\\\]]"是一個正則表達式。 外部[]表示:內部符號之一。 這些是() 另外,您要匹配[] 但是您必須在它們前面加上\\\\ ,因為它們具有特殊含義(“其中之一”)。

您需要轉義()[] 您可以使用\\\\做到這一點。 就像是,

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

輸出是

I need this message  without this

您需要在replaceAll語句中的[和()之前添加雙反斜杠:

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

(僅供參考,單個\\不會起作用,因為它將評估)作為轉義的特殊字符,)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM