Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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

by QM (Parson)
on Mar 05, 2018 at 10:07 UTC ( [id://1210345]=note: print w/replies, xml ) Need Help??


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 (Archbishop) 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:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1210345]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-04-18 01:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found