java 替换方括号java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10961957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:14:01  来源:igfitidea点击:

replace square brackets java

javareplacebrackets

提问by Ema

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?"

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

it should become:

它应该变成:

"Hello, this is an example, can you help me?"

“你好,这是一个例子,你能帮帮我吗?”

回答by Sean Patrick Floyd

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

What this does is to replace all occurrences of a regular expression with the empty 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

回答by nhahtdh

This should work:

这应该有效:

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

回答by Mohammed Shaheen MK

Please use this,

请使用这个,

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