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

Hi, I have a string that has the characters ::: to split words , is it possible to split every 3rd occurrence with regex and place it into an array, example below.

my $string = "firstname1:::surname1:::middlename1:::firstname2:::surna +me2:::middlename2:::firstname3:::surname3:::middlename3"; my @arr;
How my array should look:
$arr[0] output: firstname1:::surname1:::middlename1 $arr[1] output: firstname2:::surname2:::middlename2 $arr[2] output: firstname3:::surname3:::middlename3
Thanks.

Replies are listed 'Best First'.
Re: Regex split at number of occurrence
by tybalt89 (Monsignor) on Jul 02, 2018 at 15:17 UTC
    #!/usr/bin/perl # https://perlmonks.org/?node_id=1217751 use strict; use warnings; my $string = "firstname1:::surname1:::middlename1:::firstname2:::surna +me2:::middlename2:::firstname3:::surname3:::middlename3"; my @arr = $string =~ /\w+:::\w+:::\w+/g; use Data::Dumper; print Dumper \@arr;

      Of course, that also works with a junky string:

      c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $s = 'junk%%%first1:::sur1:::middle1%%junk%%first2:::sur2:::middle +2%%junk%%first3:::sur3:::middle3%%junk'; ;; my @arr = $s =~ /\w+:::\w+:::\w+/g; dd \@arr; " [ "first1:::sur1:::middle1", "first2:::sur2:::middle2", "first3:::sur3:::middle3", ]
      but the OPer doesn't say if he or she is working with a validated string or not.


      Give a man a fish:  <%-{-{-{-<

      That works thanks!
Re: Regex split at number of occurrence
by hippo (Archbishop) on Jul 02, 2018 at 16:14 UTC

    This would be a good use of natatime

    #!/usr/bin/env perl use strict; use warnings; use feature 'say'; use List::MoreUtils 'natatime'; my $string = "firstname1:::surname1:::middlename1:::firstname2:::surna +me2:::middlename2:::firstname3:::surname3:::middlename3"; my @arr; my $it = natatime (3, split (/:::/, $string)); while (my @these = $it->()) { push @arr, join ':::', @these; } say for @arr;
Re: Regex split at number of occurrence
by AnomalousMonk (Archbishop) on Jul 02, 2018 at 15:35 UTC

    Another way:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $s = 'firstname1:::surname1:::middlename1:::firstname2:::surname2:::midd +lename2:::firstname3:::surname3:::middlename3'; ;; my $match = my @ra = $s =~ m{ \G ([^:]+ (?: ::: [^:]+){2}) (?: ::: | \z) }xmsg; ;; die 'no match' unless $match; dd \@ra; " [ "firstname1:::surname1:::middlename1", "firstname2:::surname2:::middlename2", "firstname3:::surname3:::middlename3", ]


    Give a man a fish:  <%-{-{-{-<