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
2 个解决方案
#1
7
You can try this regex:
你可以尝试这个正则表达式:
\[[^\[]*\]
and replace by empty
并替换为空
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);
#2
2
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
#1
7
You can try this regex:
你可以尝试这个正则表达式:
\[[^\[]*\]
and replace by empty
并替换为空
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);
#2
2
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: