(.|n)*? is non greedy, but it can also match any characters including any form of the test string.
What you might do is limit the accepted
test string by allowing only digits 2, 3 or 4 and make the non capture group non greedy to get the “shortest” match.
The pattern matches:
(?:Non capture group to repeat as a whole
n.*testMatch a newline and in the line
testfollowed by a digit 2, 3 or 4
)*?Close the non capture group and optionally repeat non greedy
n.*test4Match a newline and a line that matches test4
See a regex demo.
Read more here: Source link