Regex – Capture multiline pattern – the shortest match

The (.|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:

  • test2 match literally
  • (?: Non capture group to repeat as a whole
    • n.*test[234] Match a newline and in the line test followed by a digit 2, 3 or 4
  • )*? Close the non capture group and optionally repeat non greedy
  • n.*test4 Match a newline and a line that matches test4

See a regex demo.

Read more here: Source link