in reply to how to replace a matched pattern in a string with a different pattern of same length?

$s = '00111100110';; $s =~ s[(1+)]['2' x length $1]e;; print $s;; 00222200110

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
  • Comment on Re: how to replace a matched pattern in a string with a different pattern of same length?
  • Download Code

Replies are listed 'Best First'.
Re^2: how to replace a matched pattern in a string with a different pattern of same length?
by BhariD (Sexton) on Jun 19, 2011 at 14:32 UTC
    Thanks!

    as I was testing the code I realize, the code that I am using is not matching the longest string of 1's

    my $string = '00110011111110111111111111111110'; $string =~ /(1{1,}1)/; print $1, "\n"; prints 11 instead of 11111111111111111

    I know to search for longest string separated by 1's, I would use =~ /(1.*1)/, but here "." will pick 0's and 1's both, and I only want 1's. I tried few other combinations but didn't seem to work. any suggestions?

      BharID:

      Look for all matches, select the longest one, and then perform your replacement. Something like (untested):

      my $string = '00110011111110111111111111111110'; my $str_to_replace; for ($string=~/(1+)/g) { my $temp = $1; $str_to_replace = $temp if length($tmp) > length($str_to_replace); } if ($str_to_replace) { my $repl = '2' x length($str_to_replace); $string =~ s/$str_to_replace/$repl/; }

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

      $s = '00110011111110111111111111111110';; my $best = [0,0];; $+[0] - $-[0] > $best->[1] and $best = [ $-[0], $+[0] - $-[0] ] while $s =~ m[(1+)]g;; substr $s, $best->[0], $best->[1], '2'x$best->[1];; print $s;; 00110011111110222222222222222220

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.