Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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

by AnomalousMonk (Bishop)
on Mar 05, 2018 at 15:52 UTC ( #1210356=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2021-04-20 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?