Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Replace characters within string

by hv (Prior)
on Sep 07, 2022 at 22:08 UTC ( [id://11146756]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11146756]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-25 10:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found