use strict;
my $str = 'Paint it white
Paint it black
Why not blue?
Or red or brown?
~1~2~3~4~5~6~7~8~9~10';
my $regex = qr/(?xsm) # free-spacing mode, DOTALL, multi-line
(?=.*?blue) # if blue isn't there, fail without delay
###### Recursive Section ######
# This section aims to balance empty lines with digits, i.e.
# emptyLine,emptyLine,emptyLine ... ~1~2~3
# The last digit block is captured to Group 2, e.g. ~3
(?= # lookahead
( # Group 1
(?: # skip one line that doesn't contain blue
^ # start of line
(?:(?!blue)[^\r\n])* # zero or more chars not followed by blue
(?:\r?\n) # newline
)
(?:(?1)|[^~]+) # recurse Group 1 OR match all non-tilde chars
(~\d+) # match a sequence of digits
)? # End Group 1
) # End lookahead.
# Group 2, if set, now contains the number of lines skipped
.*? # lazily match chars up to...
blue # match blue
.*? # lazily match chars up to...
(?(2)\2) # if Group 2 is set, match Group 2
~ # Match the next tilde
\K # drop what was matched so far
\d+ # match the next digits: this is the match
/p;
if ( $str =~ /$regex/ ) {
print "Whole match is ${^MATCH} and its start/end positions can be obtained via \$-[0] and \$+[0]\n";
# print "Capture Group 1 is $1 and its start/end positions can be obtained via \$-[1] and \$+[1]\n";
# print "Capture Group 2 is $2 ... and so on\n";
}
# ${^POSTMATCH} and ${^PREMATCH} are also available with the use of '/p'
# Named capture groups can be called via $+{name}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Perl, please visit: http://perldoc.perl.org/perlre.html