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

Hi all, I am searching for a way to find repetetive characters from a string and work with them. I have found something that works, but looking at it, it doesn't look like the right solution to me. I was hoping some of you know a better solution. Here's my code:
my @numbers = $aKnosID =~ m/([a]{2,}|[b]{2,}|[c]{2,}|[d]{2,}|[e]{2 +,}|[f]{2,}|[g]{2,}|[h]{2,}|[i]{2,}|[j]{2,}|[k]{2,}|[l]{2,}|[m]{2,}|[n +]{2,}|[o]{2,}|[p]{2,}|[q]{2,}|[r]{2,}|[s]{2,}|[t]{2,}|[u]{2,}|[v]{2,} +|[w]{2,}|[x]{2,}|[y]{2,}|[z]{2,})/g; if ( @numbers > 0 ) { #repetetive strings here; for ($i=0;$i<@numbers;$i++) { #Do something } } else { }
  • Comment on Finding / Replacing repetetive characters from a string in a Regular expression.
  • Download Code

Replies are listed 'Best First'.
Re: Finding / Replacing repetetive characters from a string in a Regular expression.
by deibyz (Hermit) on Oct 14, 2004 at 13:33 UTC
    I'm not very sure what you're trying to do, but a simple m|([a-z])(\1)+|; should be enough to catch repetitive characters.
      Sorry, that doesn't work. The solution that really works is above: grep {length > 1} $aKnosID =~ /(([a-z])\2+)/g;
Re: Finding / Replacing repetetive characters from a string in a Regular expression.
by JediWizard (Deacon) on Oct 14, 2004 at 13:29 UTC

    It looks to me like your expression is the equivilent of :

    my @numbers = $aKnosId =~ m/([a-z]{2,})/g

    Update I was totally wrong... sorry. Try this:

    my @numbers = $aKnosId =~ m/(([a-z])(?:(?=\2)[a-z])+)/g

    But then again Roy's answer is better.

    May the Force be with you
      The difference is that your expression will match two (or more) different characters, while the OP wants to match two (or more) of the same. This should do it.
      my @numbers = $aKnosId =~ /(([a-z])\2+)/g;
      Except that both captures get returned. So to fix:
      my @numbers = grep {length > 1} $aKnosId =~ /(([a-z])\2+)/g;

      Caution: Contents may have been coded under pressure.
        Thank you! Your solution works great :D.