Replace pattern with one space per character in Perl
perl, regex
Solution
One simple way is:
$text =~ s!\b(http://)([^/]+)!$1 . " " x length($2)!e;
The regexp `\b(http://)([^/]+)` matches a word boundary, the literal string `http://`, and one or more non-slash characters, capturing `http://` in `$1` and the non-slash characters in `$2`. (Note that I've used `!` as the regexp delimiter above instead of the usual `/` to avoid leaning toothpick syndrome.)
The `e` switch at the end of the `s///` operator causes the substitution `$1 . " " x length($2)` to be evaluated as Perl code instead of being interpreted as a string. It thus evaluates to `$1` followed by as many spaces as there are letters in `$2`.
Problem
Let's say I'm trying to match a URL with regular expressions: ``` $text = 'http://www.google.com/'; $text =~ /\bhttp:\/\/([^\/]+)/; print $1; # It prints www.google.com ``` I would like to replace the pattern it matches with one space for each character in it. For instance, considering the example above, I would like to end up with this text: ``` # http:// / ``` Is there a simple way to do this? Finding out how many characters the matched pattern has and replacing it with the same number of different characters? Thank you.