Question

I need to convert timestamp of the format 'h:m:s' to '0h:0m:0s' . i.e if any of hour or minute or second is single digit then add leading zero.

example-

1:6 should be converted to 01:06

1:5:6 should be converted to 01:05:06

05:6 should be converted to 05:06

What i tried?

$this_video_duration =~ s/(^|:)(\d(:|$))/0$2/g;

Please help me for this regex.

Was it helpful?

Solution 3

Your issue is that the ending : in a first match is "eating" the beginning : of the next match.

You could use zero width word boundary:

$this_video_duration =~ s/\b\d\b/0$&/g;

\b will match between \w\W or \W\w, and \d is in \w. Demo here.

OTHER TIPS

$this_video_duration =~ s/(\d+)/ length($1) >1 ? $1 : "0$1" /ge;
$x = join ':', map { sprintf '%02d', $_ } split /:/, $x;

or

$x =~ s/\d+/ sprintf '%02d', $_ /eg;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top