簡體   English   中英

替換方括號java

[英]replace square brackets java

我想用java中的“”替換方括號中的文本:

例如,我有句子

"Hello, [1] this is an example [2], can you help [3] me?"

它應該成為:

“你好,這是一個例子,你能幫助我嗎?”

String newStr = str.replaceAll("\\[\\d+\\] ", "");

這樣做是用空String替換所有出現的正則表達式。

正則表達式是這樣的:

\\[  // an open square bracket
\\d+ // one or more digits
\\]  // a closing square bracket
     // + a space character

這是第二個版本(不是OP要求的,但更好地處理空白):

String newStr = str.replaceAll(" *\\[\\d+\\] *", " ");

這樣做是用一個空格字符替換所有出現的正則表達式。

正則表達式是這樣的:

 *   // zero or more spaces
\\[  // an open square bracket
\\d+ // one or more digits
\\]  // a closing square bracket
 *   // zero or more spaces

這應該工作:

.replaceAll("\\[.*?\\]", "").replaceAll(" +", " ");

請用這個,

String str = "[How are you]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");

暫無
暫無

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

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