You can do this with regex flavours like PCRE, which support an end-of-match token (\G
) and can be set to single line matching (/s
). The idea is to match the first target by anchoring to the beginning of the line while consuming as few characters as possible (^.*?
) and then to allow further matches only at the end of previous matches, while excluding line breaks in procuring them (\G[^\r\n]*?
). See regex demo.
An expression to do that could look like this:
/(?:^.*?|\G[^\r\n]*?)\Ktext2/gs
\K
is simply used to cut out the preceeding part of matches from the result to avoid using capturing groups for singling out text2
.
To cover other aspects of line break/position matching, if you want to drop the single-line modifier (/s
), in which case .
ceases to match new-line characters, you can use a class that also matches line breaks, like [\s\S]*?
, instead of .*?
to get the initial match. See demo.
/(?:^[\s\S]*?|\G[^\r\n]*?)\Ktext2/g
If you want to use the multi-line modifier /m
specifically, in which case the caret ^
now matches at the beginning of every line, you'll have to use the anchor for the beginning of string \A
instead to match the initial target. See demo.
/(?:\A[\s\S]*?|\G[^\r\n]*?)\Ktext2/gm