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

how do I do a regex that adds a character in s tring every "x" number of characters.

ie:

$string='abchijk'; while ($string =~ s/(\w{2})(.*)$/$1\|$2/) { print "$string\n"; } should print: ab|chijk ab|ch|ijk ab|ch|ij|k

s/pre/code/ tags - dvergin 2002-04-29

Replies are listed 'Best First'.
Re: regex multiple times
by Zaxo (Archbishop) on Apr 30, 2002 at 02:09 UTC

    One way, with regexes, is:

    $string =~ s/(..)/$1|/g;
    If the string is read from a handle, there is a neat trick using a reference to an integer for $/:
    my $string; { local $/ = \2; my @pairs = <FOO>; $string = join '|', @pairs; }
    It would be good if one of the modules tieing handles to strings honored $/ accurately enough to us this on a string, but afaik they don't.

    After Compline,
    Zaxo

Re: regex multiple times
by Cyrnus (Monk) on Apr 30, 2002 at 02:30 UTC
    You were close. This will do what you intended.
    $string='abchijk'; while ($string =~ s/(\w{2})(\w)/$1\|$2/) { print "$string\n"; }
    When you were using (.*) it was matching the '|'

    John
Re: regex multiple times
by abaxaba (Hermit) on Apr 30, 2002 at 03:07 UTC
    howabout --
    (@parts) = $string=~/(\w{2})/g; print join ("|",@parts);
    ÅßÅ×ÅßÅ
    "It is a very mixed blessing to be brought back from the dead." -- Kurt Vonnegut