Replace a pattern with a single space per character in Perl

Let's say I'm trying to match URLs with regular expressions:

$text = 'http://www.google.com/'; $text =~ /\bhttp:\/\/([^\/]+)/; print $1; # It prints www.google.com 

I would like to replace the template that it corresponds to one space for each character in it. For example, having considered the above example, I would like to get this text:

 # http:// / 

Is there an easy way to do this? Find out how many characters match the pattern and replace it with the same number of different characters?

Thanks.

+4
source share
1 answer

One easy way:

 $text =~ s!\b(http://)([^/]+)!$1 . " " x length($2)!e; 

The regular expression \b(http://)([^/]+) matches the word boundary, the literal string http:// and one or more characters without a slash, capturing http:// at $1 and characters without a slash at $2 . (Note that I used ! As the regex separator above instead of the usual / to avoid the divergent toothpick syndrome .)

The switch e at the end of the s/// operator causes the substitution of $1 . " " x length($2) be replaced $1 . " " x length($2) $1 . " " x length($2) as Perl code instead of interpreting a string. Thus, it is valued at $1 , followed by as many spaces as there are letters in $2 .

+6
source

Source: https://habr.com/ru/post/1493506/


All Articles