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


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

$foo = ':{"'; $foo =~ s/([:,{])(.)/$1 $2/g; print "'$foo'\n";

If you just want a space after each of those, but not if it's the last char in a string:

1 while $foo =~ s/([:,{])([^ ])/$1 $2/g; # [^ ] is "not space"

If you want it after the last char in a string, you'll need something like:

1 while $foo =~ s/([:,{])([^ ]|$)/$1 $2/g;

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re^2: When a regexp with /g needs to be run .. twice
by AnomalousMonk (Bishop) on Mar 05, 2018 at 15:52 UTC

    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:  <%-{-{-{-<