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

I am working on a piece of code that will look for adjacent character repitions and remove them (for example, turning 'Matt' into 'Mat', 'momma' into 'moma', but leaving 'Ana' alone). Are there any efficient regexes that would work for this? My initial thoughts were to build a loop to go through each character (a-zA-Z), but there must be a better way. Thanks for all the help!

www.loungeman.com
  • Comment on Removing Adjacent Character Repititions

Replies are listed 'Best First'.
Re: Removing Adjacent Character Repititions
by BrowserUk (Patriarch) on Jan 15, 2003 at 17:55 UTC

    Use

    $string =~ tr/A-Za-z//s;
    See perlop for more info.

    Examine what is said, not who speaks.

    The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Re: Removing Adjacent Character Repititions
by broquaint (Abbot) on Jan 15, 2003 at 17:55 UTC
    Sure, how about
    my $str = "foo baa bzz"; print $str, $/; $str =~ s< ([A-Za-z]) (?:\1)+ >($1)gx; print $str, $/; __output__ foo baa bzz fo ba bz
    See man perlre for more info on regular expressions in perl.
    HTH

    _________
    broquaint

Re: Removing Adjacent Character Repititions
by bbfu (Curate) on Jan 15, 2003 at 18:01 UTC

    $string =~ s/(.)\1+/$1/g; # or... #$string =~ tr/A-Za-z0-9//s; $string =~ tr///sc; # update: use this instead

    Note that if you use tr///, you have to specify every character you want to match.

    Update: Ah, true. Thanks, BrowserUk.

    bbfu
    Black flowers blossum
    Fearless on my breath

      If you want to remove contiguous duplicates of literally every character, you don't have to specify any characters with tr///s, you just add the /c option.

      $s = 'Ttthe Qqquiicccck brroooown fox' $s =~ tr///cs print $s Tthe Qquick brown fox

      Examine what is said, not who speaks.

      The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Re: Removing Adjacent Character Repititions
by jupe (Beadle) on Jan 15, 2003 at 18:08 UTC
    you guys utterly rule. faster than i can go and get a cup of coffee, three people have answered. thank you all for your generosity!!