This single regexp might be what you're after. It uses backreferences to make sure that you match the same thing three or more times, and then keeps only the first two occurrences. All this has to happen at the end of the string.

s/(\w){2}\1+\Z/$1$1/;

Update: Perlbotics solution above is it. ;) Bah, hate it when that happens!

To get a good explanation, run the following one-liner:

perl -MYAPE::Regex::Explain -E 'say YAPE::Regex::Explain->new(qr/( \w){2}\1+\Z/)->explain();'

Update2:

So since I botched it, and the best s/// construct was already posted, I figured I may as well have a little fun with my walk of shame. :)

The following is a substr approach that is more in keeping with how life was before every programming language developed Perl-envy and incorporated its own version of regular expressions (no, Perl didn't invent them, but was a big part of popularizing them). Have a look and enjoy knowing that you live in a Perlish world instead.

use strict; use warnings; use v5.12; my $string = "abcdefggggggggggg"; my $position = length( $string ) - 1; my $find = substr $string, $position, 1; $position-- while substr( $string, $position, 1 ) eq $find; substr( $string, $position + 3, length( $string ) - ( $position + 3 ), + '') if length( $string ) - $position > 3; say $string;

Dave


In reply to Re: Regex related question by davido
in thread Regex related question by Hena

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.