Rectangle 27 0

java Regex: How to capture this (a nested group inside a repeated group)?


List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("\"[^\"\\[\\]]*\"(?=[^\\[\\]]*\\])");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group());
}
\[[^\]]*\]
  • Find all occurrences of "[^"]*" within the result of the first match. Or even use a JSON parser to read that string.

Do you think anybody who looks at this in a few months can tell what it's doing?

If strings only can occur between brackets, then you don't need to check for them at all and just use "[^"]*" as your regex and find all matches (assuming no escaped quotes).

If that doesn't work because strings could occur in other places too, where you don't want to capture them, do it in two steps.

Search for "[^"\[\]]*"(?=[^\[\]]*\]). That will match a string only if the next bracket that follows is a closing bracket. Limitation: No brackets are allowed inside the strings. I consider this ugly, especially if you look at how it would look like in Java:

Third possibility, cheating a bit:

Well, OK, there is another way, but I don't think it's a good one. I've added it to my answer.

Note
Rectangle 27 0

java Regex: How to capture this (a nested group inside a repeated group)?


Get string between [ ] and then split by comma. It's much easier.

Note