use strict;
my $str = ' BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~LOOP3 hello3~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP3 hello3~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~End stuff~
';
my $regex = qr/
(?<firstcapture> ~Start [^~]* ) #_(3)
(?<randomStuff> .*? ) #_(4)
(?<loop_first> #_(5 start)
(?:
~
(?: LOOP )
\d [^~]
)
( .*? ) # (1)
) #_(5 end)
(?:
(?<loop_middle> #_(6 start)
(?:
(?:
~
(?: LOOP )
\d [^~]
)
.*?
)*
) #_(6 end)
(?<loop_last> #_(7 start)
(?:
~
(?: LOOP )
\d [^~]
)
( .*? ) # (2)
) #_(7 end)
)?
(?<end> ~End [ ] stuff~ ) #_(8)
/mxp;
my $subst = '${firstcapture}${randomStuff}${loop_last}${loop_middle}${loop_first}${end}';
my $result = $str =~ s/$regex/$subst/rg;
print "The result of the substitution is' $result\n";
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Perl, please visit: http://perldoc.perl.org/perlre.html