java Java正则表达式匹配方括号

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

Java Regular expression matching square brackets

javaregex

提问by Pruthvi Raj Nadimpalli

I'm trying to do the following using regular expression (java replaceAll):

我正在尝试使用正则表达式(java replaceAll)执行以下操作:

**Input:**
Test[Test1][Test2]Test3

**Output**
TestTest3

In short, i need to remove everything inside square brackets including square brackets.

简而言之,我需要删除方括号内的所有内容,包括方括号。

I'm trying this, but it doesn't work:

我正在尝试这个,但它不起作用:

\[(.*?)\]

Would you be able to help?

你能帮忙吗?

Thanks,
Sash

谢谢,
腰带

回答by Rizwan M.Tuman

You can try this regex:

你可以试试这个正则表达式:

\[[^\[]*\]

and replace by empty

并替换为空

Demo

演示

Sample Java Source:

示例 Java 源代码:

final String regex = "\[[^\[]*\]";
final String string = "Test[Test1][Test2]Test3\n";
final String subst = "";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);

回答by Tim Biegeleisen

Your original pattern works for me:

你的原始模式对我有用:

String input = "Test[Test1][Test2]Test3";
input = input.replaceAll("\[.*?\]", "");
System.out.println(input);

Output:

输出:

TestTest3

Note that you don't need the parentheses inside the brackets. You would use that if you planned to capture the contents in between each pair of brackets, which in your case you don't need. It isn't wrong to have them in there, just not necessary.

请注意,您不需要括号内的括号。如果您计划捕获每对括号之间的内容,您将使用它,在您的情况下您不需要。把它们放在那里并没有错,只是没有必要。

Demo here:

演示在这里:

Rextester

雷克斯特