#!/usr/bin/perl use strict; use warnings; use 5.014; my @stops = (2,6); # group by 2 then 4 (6 == 2 + 4) my $tag = '___'; for ('ATCGGATCTGGC', 'A-C-G--CTGGC') { my $seq = $_; for our $s (@stops) { # necessary to use 'our' instead of 'my' $seq =~ s/ ( # begin capture (??{ # dynamic regex "(?:[TAGC][^TAGC]*)" . # group to apply quantifier to "{" . ($s-1) . "}" . # quantifier "[TAGC]" # end token }) # end dynamic reference ) # end capture /$1$tag/x; # end of substitution } $seq =~ s/__-+/__/g; say $seq; } __END__ C:\Old_Data\perlp>perl dynamic_regex.pl AT___CGGA___TCTGGC A-C___G--CTG___GC C:\Old_Data\perlp>