1

I want to use regex to create substrings containing characters between "[" and "]" brackets but without the brackets themselves.

For example:

This is a String with [the substring I want].

The regex I use is as follows:

\[.*?\]

And it works fine except for the fact that it also includes brackets in the match. So the result I get is:

[the substring I want]

instead of

the substring I want

Yes, I can very easily get rid of the brackets afterwards but is there any way to not match them at all?

Arqan
  • 376
  • 1
  • 3
  • 14

1 Answers1

2

Use "lookarounds":

String test = "This is a String with [the substring I want].";
//                          | preceding "[", not matched
//                          |      | any 1+ character, reluctant match
//                          |      |  | following "]", not matched
//                          |      |  | 
Pattern p = Pattern.compile("(?<=\\[).+?(?=\\])");
Matcher m = p.matcher(test);
if (m.find()) {
    System.out.println(m.group());
}

Output

the substring I want
Mena
  • 47,782
  • 11
  • 87
  • 106