Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Regex match iterative grouping

by SamCG (Hermit)
on Apr 06, 2006 at 16:23 UTC ( [id://541665]=perlquestion: print w/replies, xml ) Need Help??

SamCG has asked for the wisdom of the Perl Monks concerning the following question:



Okay, the code:
perl -e "@re='abcdefg'=~/(..)/g;print join ',', @re;" #prints ab,cd,ef
but, what if I don't want the position to set to after the last match, but to one character after the beginning of the last match to produce ab,bc,cd,de,ef,fg? I've tried a few strange variants of adding code into the expression to alter the 'abcdefg' midway, but these don't seem to produce the results I want.

perl -e "$_='abcdefg';@re=/(..)(?{reverse;chop;reverse;})/g;print join + ',', @re;" ab,cd, perl -e "$_='abcdefg';@re=/(..)(?{$_=substr($_,1)})/g;print join ',', +@re;" bc,ef,
No particular purpose here other than just to wield regexes better, so if there are practical reasons this is ludicrous feel free to tell me.

-----------------
s''limp';@p=split '!','n!h!p!';s,m,s,;$s=y;$c=slice @p1;so brutally;d;$n=reverse;$c=$s**$#p;print(''.$c^chop($n))while($c/=$#p)>=1;

Replies are listed 'Best First'.
Re: Regex match iterative grouping
by Ido (Hermit) on Apr 06, 2006 at 16:35 UTC
Re: Regex match iterative grouping
by sfink (Deacon) on Apr 06, 2006 at 17:10 UTC
    Adjust the quotes for your shell:

    perl -le '$_ = "abcd"; while (/(..)/g) { print $1; --pos }'

    Or closer to your exact question:

    perl -le '$_ = "abcdefg"; while (/(...)/g) { print $1; pos($_) -= leng +th($1); pos($_)++ }'
    You might be able to do that in a list-context match with an embedded expression, but that would be too scary for me.
      Thank you, both solutions work, though I will have to work on understanding Ido's a bit better.

      Note that as far as "adjusting my quotes to my shell", that technique doesn't work on my <Windows XP> shell. Inverting them (double-quotes surrounding all executable code, with either single quotes in the middle or escaped double-quotes) does work.


      -----------------
      s''limp';@p=split '!','n!h!p!';s,m,s,;$s=y;$c=slice @p1;so brutally;d;$n=reverse;$c=$s**$#p;print(''.$c^chop($n))while($c/=$#p)>=1; =1;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-03-28 18:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found