0

What is the correct way to match all the instances of [ ] in a string.

I'm trying with

String content = "ZZZ AA PP [AA] Q[QQ] AAA ZZ";

  String string = "\\[.*\\]";
  Pattern pattern = Pattern.compile(string);
  Matcher matcher = pattern.matcher(content);

It matches from [AA] Q[QQ] as a single instance whereas I want to get both the instances between [].

Any help would be appreciated.

Bhavesh
  • 11
  • 4

3 Answers3

0

You can try making the regex non-greedy by using this:

String content = "ZZZ AA PP [AA] Q[QQ] AAA ZZ";
String string = "(\\[.*?\\])";
Pattern pattern = Pattern.compile(string);
Matcher matcher = pattern.matcher(content);

int count = 0;
while (matcher.find())
    count++;

System.out.println("Found " + count + " matches.");

Output:

Found 2 matches.
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Use this regex

\[.*?\]

It uses the lazy mode of the quantifier instead of the greedy mode. (Greedy mode is used by default)

The lazy mode of quantifiers is a counterpart to greedy. It can be enabled by putting a question mark '?' after the quantifier, so it becomes ? or +? or even ?? for '?'.

What it is doing:

In lazy mode the engine tries to repeat as little as possible.

Huntro
  • 322
  • 1
  • 3
  • 16
0

It matches [AA] Q[QQ] because all regex patterns are greedy by default, trying to match the biggest groups they can. So when it sees the first ] it goes on to see if it can make the group even bigger.

There are two ways of doing what you want. One is using a reluctant quantifier \\[.*?\\]. The other is capturing everything, except the right-side bracket \\[[^\\]]*\\].

coladict
  • 4,799
  • 1
  • 16
  • 27