Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
Java Regular expression matching square brackets

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

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

\[\w+]

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!