# 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 '$&')"; } } #### $n = 4 matched 'fred2...' at pos 12 (gobbled '.....fred1..fred') matched 'fred3....' at pos 20 (gobbled '2...fred') $n = 5 matched 'fred1..' at pos 5 (gobbled '.....fred1') matched 'fred3....' at pos 20 (gobbled '..fred2...fred3')