How to replace a string with a dynamic string

Case 1

I have a string of alphabets , for example fthhdtrhththjgyhjdtygbh. Using regex, I want to change it to ftxxxxxxxxxxxxxxxxxxxxx, i.e. Save the first two letters and replace the rest with x.

After a lot of searches, I achieved this:

s/^(\w\w)(\w+)/$1 . "x" x length($2)/e;

Case 2

I have a string of alphabets , for example sdsABCDEABCDEABCDEABCDEABCDEsdf. Using regex, I want to change it to sdsABCDExyxyxyABCDEsdf, i.e. Save the first and last ABCDEand replace ABCDE in the middle with xy. I have achieved this:

s/ABCDE((ABCDE)+)ABCDE/$len = length($1)\/5; ABCDE."xy"x $len . ABCDE/e;

Problem . I am not happy with the solution to this problem. Is there a better or neat solution to this problem.

Contraint . Only one regular expression needs to be used.

, . , , - .

+4
2

1: hider regex

" " , , . /e :

my $str = 'fthhdtrhththjgyhjdtygbh';

$str =~ s/(?<=\w{2})\w/x/g;

print $str;

:

ftxxxxxxxxxxxxxxxxxxxxx

2:

Lookbehind, Lookahead Assertion ABCDE, :

my $str = 'sdsABCDEABCDEABCDEABCDEABCDEsdf';

$str =~ s/(?<=(ABCDE))\1(?=\1)/xy/g;

print $str, "\n";

:

sdsABCDExyxyxyABCDEsdf
+1

, \1 ,

s|(ABCDE)\K (\1+) (?=\1)| "xy" x (length($2)/length($1)) |xe;
+1

All Articles