Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Replacing matches within string without splitting.

by AnomalousMonk (Canon)
on Jan 02, 2013 at 18:37 UTC ( #1011332=note: print w/replies, xml ) Need Help??


in reply to Replacing matches within string without splitting.

Using only look-arounds and no captures. Express the conditions: insert '0' at every point that is:

  • not after a digit; and
  • before a solitary digit.

perl -wMstrict -le "my @strs = ( '1,2,3,4', '8,9,10,11', '7,8,9,10', '12,13,14,15', '1,23,456', '123,45,6', ); ;; my $not_after_digit = qr{ (?<! \d) }xms; my $before_solitary_digit = qr{ (?= \d (?! \d)) }xms; ;; for my $s (@strs) { printf qq{'$s' -> }, $s; $s =~ s{ $not_after_digit $before_solitary_digit }{0}xmsg; print qq{'$s'}; } " '1,2,3,4' -> '01,02,03,04' '8,9,10,11' -> '08,09,10,11' '7,8,9,10' -> '07,08,09,10' '12,13,14,15' -> '12,13,14,15' '1,23,456' -> '01,23,456' '123,45,6' -> '123,45,06'