http://qs321.pair.com?node_id=1210356


in reply to Re: When a regexp with /g needs to be run .. twice
in thread When a regexp with /g needs to be run .. twice

But no while-loop at all is needed (and no captures) if lookarounds are used. (I'm substituting  '.' rather than a space in the examples below for greater clarity — I hope.)

Inserting something after each character in the class including when it's at the end of the string:

c:\@Work\Perl\monks>perl -wMstrict -le "my @foos = (':X,{X', ':X,{'); ;; for my $foo (@foos) { printf qq{'$foo' -> }; $foo =~ s( (?<= [:,{]) ){.}xmsg; print qq{'$foo'}; } " ':X,{X' -> ':.X,.{.X' ':X,{' -> ':.X,.{.'
Inserting something after each character in the class except when it's at the end of the string:
c:\@Work\Perl\monks>perl -wMstrict -le "my @foos = (':X,{X', ':X,{'); ;; for my $foo (@foos) { printf qq{'$foo' -> }; $foo =~ s( (?<= [:,{]) (?= .) ){.}xmsg; print qq{'$foo'}; } " ':X,{X' -> ':.X,.{.X' ':X,{' -> ':.X,.{'
(These examples work with Perl 5.8. Note that with the Perl 5.10+ regex  \K operator, the  (?<= [:,{]) terms in both examples can simplify to  [:,{] \K instead.)

Update: Note also that in all cases  (?! \z) can perhaps better express the "except at the end of the string" requirement than  (?= .) — and may even be slightly faster!


Give a man a fish:  <%-{-{-{-<