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

I have the following string, where certain characters are repeated. I want to retain the first character and replace the immediately repeating characters with "*". But the below code works for the first occurrence of a particular character and not again if the same characters repeat at a latter point.
my $str = "Foooboooobaaar"; while($str =~ /(\w)(\1+)/gi) { print "\nInside while concat_str -- $1 ---- $2 ---> $1.$2"; $str_concat = $1.$2; $str_rep_concat = $1.'*'; $str=~ s/$str_concat/$str_rep_concat/gi; } print "\n$str";
The above code finds a repeated character only once i.e. the "o" after "F". If it is repeated again it is being ignored in this case the "o"s after b. How to find the all the repeated characters and have them substituted. Thanks

Replies are listed 'Best First'.
Re: Replace repeated characters with *
by GrandFather (Saint) on Jul 03, 2009 at 11:44 UTC

    A simple regular expression makes it easy:

    use strict; use warnings; my $str = "Foooboooobaaar"; $str =~ s/(.)\1+/$1*/g; print "\n$str";

    Prints:

    Fo*bo*ba*r

    True laziness is hard work
      Thanks. Plain regex makes it too easy.