user2989653 user2989653 - 3 months ago 7
Perl Question

In perl, how can I substitute only after and before certain character sequences?

For example, if I want to substitute all occurrences of double vowels to a single capital vowel only if they occur between

<begin>
and
<end>
, how would I do that?

Noot thiis <begin> buut theese need too bee chaanged <end> buut noot heeree eitheer


should become

Noot thiis <begin> bUt thEse nEd tO bE chAnged <end> buut noot heeree eitheer

Answer

Regular expression for case <begin> and <end> can occur several times:

$_="Noot thiis <begin> buut theese need too bee chaanged <end> buut noot heeree eitheer<begin>and thiis <end>";
s/(?:<begin>|\G(?!^))(?(?=<end>)|.)*?\K([a-z])(\1)/uc($1)/ge;
print;

Result

Noot thiis <begin> bUt thEse nEd tO bE chAnged <end> buut noot heeree eitheer<begin>and thIs <end>

Demo on regex101.com

Regular expression:

(?:<begin>|      # Search from <begin>
   \G            # or position of last match
   (?!^)         #    excluding start of string
)      
(?(?=<end>)|     # If found <end> then test expression between `)` and `|`.
                 # as it is empty (not a <end>)
                 #  - then not matched - end of current search.
  .)*?           # if NOT <end> then any symbol. too many times
\K               # Matched only be considered from this position
                 # replace only after this position
([a-z])(\1)      # 1-character and 1 same
Comments