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

Hello fellow monks,

I have a string that I need to break into 4 byte words, for example:

AR12CR32LC85AR16
AR12 CR32 LC85 AR16

Does anyone have a suggestions for a regular expression I might try Thanks again

Replies are listed 'Best First'.
Re: Reg Exp Help
by waswas-fng (Curate) on Aug 28, 2002 at 19:04 UTC
    $input = "AR12CR32LC85AR16"; @fourbytes= unpack("A4" x (length($input)/4), $input);

    Fast.

    -Waswas
    Edited, whoops missed the example data with spaces in it, this only works for the first example data, but it is damn fast.
      @fourbytes= unpack("A4" x (length($input)/4), $input);
      Careful: this will strip spaces of the end of each string. Use "a4" instead of "A4" as a template to prevent that.
        ++, nice catch.

        -Waswas
      I believe the bit with spaces in it was sample output data, not sample input data, so your post works. Plus it is the canonical way to do this kind of thing, so ++

      Makeshifts last the longest.

Re: Reg Exp Help
by fglock (Vicar) on Aug 28, 2002 at 18:26 UTC

    /(.{4})/g does the job:

    perl -e '@a = "AR12CR32LC85AR16" =~ /(.{4})/g; print join(" ", @a)' AR12 CR32 LC85 AR16
Re: Reg Exp Help
by cfreak (Chaplain) on Aug 28, 2002 at 18:43 UTC
Re: Reg Exp Help
by DamnDirtyApe (Curate) on Aug 28, 2002 at 18:26 UTC

    The following works for your example, at least:

    my $str = 'AR12CR32LC85AR16' ; my @arr = map { /(.{4})/g } $str ; print "@arr\n" ;

    Be careful with the distinction between 4-byte and 4-character words -- I believe it depends on what character encoding you use.

    Update: OK, that map probably wasn't a good idea... go with the post previous to this instead.


    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche