Is there a way to replace a substring with the same number of X characters with its length?

I am trying to match some lines in a file with Perl with a regex that will judge them with the same number of X characters as the length of the original string. For example, a file might contain something like:

"the quick brown hello world fox jumps over the world" etc. etc.

      

and a dictionary which, for example, has strings like: "hello world"

and what I will load into the array before.

I would like to get the following result:

"the quick brown XXXXX XXXXX fox jumps over the world" etc. etc.

      

+3


source to share


3 answers


You must use modifier /e

substitution to replace expression along with repetition operatorx

The code looks like this. The construct \Q

... \E

should avoid any non-letter letters so that they are interpreted literally instead of regex metacharacters

use strict;
use warnings;
use 5.010;

my $s = 'the quick brown hello world fox jumps over the world';

my $pattern = 'hello world';

$s =~ s/(\Q$pattern\E)/'X' x length $1/e;

say $s;

      

Output

the quick brown XXXXXXXXXXX fox jumps over the world

      


Update



If you want to keep the space in the replaced string, you will need two nested note replacements like

use strict;
use warnings;
use 5.014;

use Data::Dump;

my $s = 'the quick brown hello world fox jumps over the world';

my $pattern = 'hello world';

$s =~ s{(\Q$pattern\E)}{ s/(\S+)/'x' x length($1)/egr }e;

say $s;

      

Output

the quick brown xxxxx xxxxx fox jumps over the world

      

or if you are using a very old version of Perl (prior to v5.14) you need this

$s =~ s{(\Q$pattern\E)}{ (my $r = $1) =~ s/(\S+)/'x' x length($1)/eg; $r }e;

      

+1


source


Not.

However, your language may have a regex replacement function that accepts a callback. Then you can do something like this:



>>> re.sub(r'o+b', lambda m: 'x' * len(m.group(0)), 'foobar')
'fxxxar'

      

+3


source


Less elegant than ThiefM's answer (Python):

import re
str_to_replace = 'hello world'
print re.sub(str_to_replace, re.sub('\w', 'x', str_to_replace), \
    "the quick brown hello world fox jumps over the world")

# another option 
print "the quick brown hello world fox jumps over the world".replace(str_to_replace, re.sub('\w', 'x', str_to_replace))

      

OUTPUT

the quick brown xxxxx xxxxx fox jumps over the world

      

PHP solution for @ rubenrp81:

<?php
$msg = "the quick brown hello world fox jumps over the world";
$str = "hello world";
$rep = preg_replace("/\w/", "x", $str);
$patt = "/$str/";
$res = preg_replace($patt, $rep, $msg);
echo $res; // prints: "the quick brown xxxxx xxxxx fox jumps over the world"
?>

      

0


source







All Articles