$str =~ s/((?=N-+)(?:N)(?:-*?))(-{1,$maxLen}B)/$1 . ('B' x length $2)/eg; $str =~ s/(B-{1,$maxLen})(?=-*(N|$))/'B' x length $1/eg;