Search code examples
regexperlstringreplacedigits

Perl: replace consecutive digits with their count


My first questions here.

I have a string of digits like 55111233

as you can see 5 is consecutive twice, 1 thrice 2 once and 3 twice.

I want it to be replaced into 52132132

in general number1<count>number2<count>...numbern<count>

Please guide me.


Solution

  •  $digits = "55111233";
     $digits =~ s/((\d)\2*)/$2 . length($1)/ge;
     print $digits;