note
ww
NOT a general solution, unless all cases closely match the sample presented (which doesn't seem to show any reasonable use of a regex to solve the problem. For a prime example, why would you do the unnecessary work of dividing the word "chapter" into a literal fragment and a captured <c>[a-z]*</c> class? This way lies madness!
<p>OTOH, many will think this plodding, literal-minded code mad.... or at best, inelegant. So be it... in the name of a clear and explicit demo of an algorithm implemented more gracefully by others, above:</p>
<c>#!/usr/bin/perl
use 5.016;
use Data::Dumper;
# 1030798
my $str = "chapter 1,2,3"; # out: "chapter 1, chapter 2, chapter 3"
my @arr = split / /,$str; # split to 2 element array, "chapter" & "1,2,3"
my @chaptnums = split /,/,$arr[1];
for my $elem(@chaptnums) {
print "$arr[0] $elem"; # e.g. "chapter " . num
if (scalar $elem != (1+$#chaptnums) ) { # not the last @chaptnums element?
print ", ";
} else {
print "\n";
}
}
=head EXECUTION
C:>1030798.pl
chapter 1, chapter 2, chapter 3
=cut</c>
<p>Again, CAUTION: The code above is NOT how to do the job; it's for instruction purposes, only.</p>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-352046">
<br><center>If you didn't program your executable by toggling in binary, it wasn't really programming!</center><br>
</div></div>
1030798
1030798