/\x26\x67(?!\x26\x67)(.(?!\x26\x67)){6}.{2}/s #### perl -le 'print for map { /ab(?!ab)(.(?!ab)){2}.{2}/s ? $& : () } @ARGV' abhjabdf abasdasd abdasdadsab ababblah OUTPUTS: abasda abdasd abblah #### / \x26\x67 # Starting sequence (let's call it AB) (?!\x26\x67) # Exclude double starting seqeuence, e.g. ABAB (?: # non-capture .(?!\x26\x67) # Any character that's not followed by the sequence ){6} # Need N-2 of these .{2} # And the last two characters can be anything. # note we know they're not AB because otherwise the # (N-2)th item in the previous part wouldn't have matched /sx # Enable comments, and make . mean everything #### my $marker = '&g'; my $N = 8; my $n1 = $N-2; /$marker(?!$marker)(?:.(?!$marker)){$n1}.{2}/s