LeukvoorJ has asked for the wisdom of the Perl Monks concerning the following question:

I would like to find all the double letters in a string and replace them with the same letter + another character. I tried:

$string =~ s/.{2}/.2/gi;

But that doesn't work. I want to f.e. 'll' to become 'l2'. Can that be easily done?

Thanks in advance,

J

Replies are listed 'Best First'.
Re: perl search and replace
by japhy (Canon) on Jun 06, 2006 at 16:33 UTC
    Yes it can, but your s/// fails on both accounts: it doesn't match duplicated letters, and it doesn't keep track of what character that was. Here is code that matches duplicated letters and replaces the second one with a '2':
    $string =~ s/([a-zA-Z])\1/${1}2/g;
    Note these things:
    • [a-zA-Z] matches a lowercase or uppercase English letter
    • ([a-zA-Z]) captures that letter to the backreference \1 (and later, to $1)
    • \1 matches whatever is stored in backreference \1 (the specific letter matched)
    • ${1}2 is the variable $1 (how you retrieve backreference \1 outside a regex) followed by the number 2 -- the reason I have $1 in braces (${1}) is so that Perl doesn't see $12 as the scalar variable $12
    If you don't care about case, you can use the /i modifier, like so:
    $string =~ s/([a-z])\1/${1}2/ig;
    Please read perlretut for more.

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: perl search and replace
by thundergnat (Deacon) on Jun 06, 2006 at 17:13 UTC

    You can generalize it for any number of repeated characters too.

    while ( my $string = <DATA> ) { $string =~ s/(.)(\1+)/$1.length($1.$2)/ge; print $string; } __DATA__ Balloon bookkeeper Wheeeee!!!

    Output:

    Bal2o2n bo2k2e2per Whe5!3
Re: perl search and replace
by vkon (Curate) on Jun 06, 2006 at 16:36 UTC