# 0 5 10 15 20 25 30 35 # ' ' ' ' ' ' ' ' $_ = q{.....fred1..fred2...fred3....fred4..}; # ----++++----||||----||||----++++---- $n = 4 # -----||||+-----+++++||||-+++++-----+ $n = 5 my $capture = qr([0-9]\.+); # the (....) in the OP's specification for my $n ( 4, 5 ) { say "\$n = $n"; while ( m[\G(?:.{$n})*?(?=fred($capture)).{0,$n}]g ) { say " matched 'fred$1' at pos @{[pos($_)-$n]} (gobbled '$&')"; } }