How can I get multiple Java regex matches only on specific lines

There is an API that I call that I cannot change. That is, I cannot do this as two consecutive regular expressions or something like that. The API is written something like this (simplified, of course):

void apiMethod(final String regex) {
    final String input = 
        "bad:    thing01, thing02, thing03 \n" +
        "good:   thing04, thing05, thing06 \n" +
        "better: thing07, thing08, thing09 \n" +
        "worse:  thing10, thing11, thing12 \n";

    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

    final Matcher matcher = pattern.matcher(input);

    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }
}

I call it something like this:

apiMethod("(thing[0-9]+)");

I want to see six lines printed, one for each item from 04 to 09 inclusive. I have not succeeded yet. Some things I tried did not help:

  • "(item [0-9] +)" - This corresponds to all 12 things that I do not want.
  • "^ (?: good | better): (item [0-9] +)" - This only matches things 4 and 7.
  • "^ (? :( ?: good | better) :. *) (item [0-9] +)" - This only matches things 6 and 9.
  • "(?: (?: ^ good: | ^ better: |,) *) ( [0-9] +)" - , 1 10.

, , . , .

, , , "thing [0-9] +", , "good:" "better:".

, , , , .

+4
1

\G ( ):

(?:\G(?!^),|^(?:good|better):)\s*(thing[0-9]+)

\G , , .


, :

(?<=^(?:good|better):.{0,1000})(thing[0-9]+)
+5

Source: https://habr.com/ru/post/1689091/


All Articles