简体   繁体   English

替换方括号java

[英]replace square brackets java

I want to replace text in square brackets with "" in java: 我想用java中的“”替换方括号中的文本:

for example I have the sentence 例如,我有句子

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

it should become: 它应该成为:

"Hello, this is an example, can you help me?" “你好,这是一个例子,你能帮助我吗?”

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

What this does is to replace all occurrences of a regular expression with the empty String. 这样做是用空String替换所有出现的正则表达式。

The regular expression is this: 正则表达式是这样的:

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

Here's a second version (not what the OP asked for, but a better handling of whitespace): 这是第二个版本(不是OP要求的,但更好地处理空白):

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

What this does is to replace all occurrences of a regular expression with a single space character. 这样做是用一个空格字符替换所有出现的正则表达式。

The regular expression is this: 正则表达式是这样的:

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

这应该工作:

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

Please use this, 请用这个,

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

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

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