-1

I am trying to get a substring from square brackets in a string, I tried multiple regexes but nothing works.

I tried multiple regexes and code from multiple stackoverflow posts but nothing works.

String mydata = "some string with [the data i want] inside";
Pattern pattern = Pattern.compile("[(.*?)]");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(1));
    output = output.replace("%item%", matcher.group(1));
}

It should return "the data i want" but instead it says that no pattern was found.

1 Answers1

0

You need to escape the [] characters so they are seen as literal square brackets.

Using this as your regex should work: \\[(.*?)\\]

Bill
  • 1,407
  • 10
  • 18