partida partida - 2 months ago 7
Perl Question

How to achieve replacement using regular expression?

$test="111222333345555";


How to replace the digit of same repeated digits to 't'?

That is, how to get
"11t22t333t4555t"
using a regular expression?

Answer

If you want to replace when there are 2 or more same consecutive digits:

#!/usr/bin/perl
use Modern::Perl;

my $test = "11222333345555";
$test =~  s/((\d)\2*)\2/$1t/g;
say $test;

Output:

1t22t333t4555t

Explanation:

(       : start group 1
  (     : start group 2
    \d  : a digit
  )     : end group 2
  \2*   : backreference on group 2 (ie: same digit) 0 or more times
)       : end group 1
\2      : backreference on group 2