in reply to Regex question - either starts, or has newline prefixing?

You said: or the line starts with \n.

This makes me wonder if part of the problem is conceptual: Generally, better, IMO, to think of \n as the end of a line (and, in the case of the data you present, the end of the previous line).

Combining that notion with the comment above re slurping, would something like this demo be simpler?

my $flag = 0; # TRUE when in a sub header or sub-sub header my @rry = <DATA>; for my $rry(@rry) { if ( $rry =~ /\A={3,4}sub.*?={3,4}$/ ) { $flag = 1; print $rry . "\n"; next; } if ( $rry =~ /\A[^=].*/ && $flag == 1 ) { print $rry . "\n"; } else { $flag=0; next; } }

... and it seems to work. Output with your sample as __DATA__

===sub header=== [[testing]] ====sub-sub header==== bla bla ===sub header=== [[testing]] sub-sub header bla bla

For your purposes, this (slightly modified) might well be in a sub, triggered by a match on more than two "=" signs.

Update:   Attributed quote in the first graf and added last para.