9

I'm trying to do the following using regular expression (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

Pruthvi Raj Nadimpalli
  • 1,335
  • 1
  • 15
  • 30

3 Answers3

14

You can try this regex:

\[[^\[]*\]

and replace by empty

Demo

Sample Java Source:

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);
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
3

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

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0
\[\w+]

This works for me, this regex matches all the words which are enclosed in square brackets.

Karan_raj
  • 1
  • 4