in reply to Replace characters within string

For the third part, if I understand the requirement correctly, you could achieve it with something like this:

$seq =~ s{ ([^U]) (?# anything other than U can be the "bracketing" character) (U+) (?# match one or more Us) (?=\1) (?# followed by the bracketing character again) }{ # replace the bracketing character and the Us that follow it # with an equal number of copies of the bracketing character $1 x (1 + length($2)) }xeg; # replace all embedded sequences of Us in one go

Note that this uses a lookahead to match the second copy of the bracketing character, to ensure that all matches can be replaced with a single invocation - I assume we want to allow "IUIUI" to be translated to "IIIII".

The same approach can also be used to simplify the head and tail matches:

$seq =~ s{^(U+)}{"I" x length($1)}eg; $seq =~ s{(U+)$}{"O" x length($1)}eg;

Note that I have ignored your assertion in the first case that the sequence of initial Us must be followed by one of I, O, P, B, M since that appears to be guaranteed; I've also ignored the assertion in the second case that the sequence of final Us must be preceded by I or O, since you don't anywhere say that that is required. (If it _is_ required, I'd use a lookbehind for that assertion.)

Hope this helps