替换正则表达式 java 中 [ 和 ] 之间的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12664392/
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 09:45:22  来源:igfitidea点击:

Replace everything between [ and ] in regex java

javaregex

提问by Sai Sunder

I need to remove everything between [ ].

我需要删除[ ].

Example:

例子:

My Input :ab[cd]e

我的输入:ab[cd]e

Expected Output :abe.

预期输出:abe



I tried using \[and \], but it is reported as an illegal escape sequence.

我尝试使用\[and \],但它被报告为非法转义序列。

Can anyone please help me with this.

任何人都可以帮我解决这个问题。

P.S.: I am using Java 1.7.

PS:我使用的是 Java 1.7。

回答by Jo?o Silva

Use String#replaceAll:

使用String#replaceAll

String s = "ab[cd]e";
s = s.replaceAll("\[.*?\]", ""); // abe

This will replace [, ], and everything in between with an empty string.

这将用空字符串替换[]和 之间的所有内容。

回答by Tadgh

Try the replaceAll method

尝试 replaceAll 方法

str = str.replaceAll("\[.*?\]","")