4

Case 1.

I have a string of alphabets like fthhdtrhththjgyhjdtygbh. Using regex I want to change it to ftxxxxxxxxxxxxxxxxxxxxx, i.e, keep the first two letters and replace the rest by x.

After a lot of googling, I achieved this:

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

Case 2.

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

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

Problem : I am not happy with my solution to the mentioned problem. Is there any better or neat solution to the mentioned problem.

Contraint : Only one regex have to be used.

Sorry for the poor English in the title and the body of the problem, english isn't my first language. Please ask in comments if anything is not clear.

2
  • What's the problem you have with your existing solution? Commented Sep 4, 2014 at 13:23
  • It's not, um, neat in my opinion. very complex regexes. Commented Sep 4, 2014 at 13:25

2 Answers 2

1

Task 1: Simplify the password hider regex

Use a Positive Lookbehind Assertion to replace all word characters preceded by two other word characters. This removes the need for the /e Modifier:

my $str = 'fthhdtrhththjgyhjdtygbh';

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

print $str;

Outputs:

ftxxxxxxxxxxxxxxxxxxxxx

Task 2: Translate inner repeated pattern regex

Use both a Positive Lookbehind and Lookahead Assertion to replace all ABCDE that are bookended by the same string:

my $str = 'sdsABCDEABCDEABCDEABCDEABCDEsdf';

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

print $str, "\n";

Output:

sdsABCDExyxyxyABCDEsdf
Sign up to request clarification or add additional context in comments.

Comments

1

One regex, less redundancy using \1 to refer to first captured group,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.