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

Hi,

I have a string that I'm trying to group the items so that I'm able to use @$0 to retrieve N number of items for use elsewhere.

1 2=3 4=5 1 2=3 and 4=5

I could just put a delimiter between the groups and use split on the modified string, but I would like it as a single regex - if that is possible.

% perl -e '$str = "1 2=3 4=5"; print "$str\n"; $str =~ s/(\w+[\w\s]*=\ +w+)(?:\s)*/$1\|/g; print "$str\n"; print "Should look like: 1 2=3|4=5 +|\n"' 1 2=3 4=5 1 2=3|4=5| Should look like: 1 2=3|4=5|

Something like so. (note: nonworking code)

perl -e '$str = "1 2=3 4=5"; print "$str\n"; $str =~ m/(\w+[\w\s]*=\w+ +)(?:\s)*/g; print "$_\n" foreach @$0;' 1 2=3 4=5 1 2=3 4=5

UPDATE: The number of items is variable. i.e. "1 2 3 2 6=7 2=4 j=384923 34 43 j 3=6". Given that string I would need grouping like so:

1 2 3 2 6=7 2=4 j=384923 34 43 j 3=6

Here is the code that works:

perl -e '$str = "1 2 3 2 6=7 2=4 j=384923 34 43 j 3=6"; print "$_\n" +foreach ($str =~ m/(\w+[\w\s]*=\w+)/g);' 1 2 3 2 6=7 2=4 j=384923 34 43 j 3=6

Jason L. Froebe

Team Sybase member

No one has seen what you have seen, and until that happens, we're all going to think that you're nuts. - Jack O'Neil, Stargate SG-1

Replies are listed 'Best First'.
Re: regex grouping
by Roy Johnson (Monsignor) on Nov 02, 2005 at 18:31 UTC
    Something like this?
    $_ = '1 2=3 4=5'; for my $up_to_3 (/(?:\W*\w+){1,3}/g) { print $up_to_3, "\n"; }
    Update: oh, you want each grouping to start with a \w, and end with an equal sign and the number following it.
    $_ = '1 2 3 2 6=7 2=4 j=384923 34 43 j 3=6'; for my $foo (/(?:\w[^=]*=\w+)/g) { print $foo, "\n"; }

    Caution: Contents may have been coded under pressure.
      thanks! I've modified the original script to reflect your for loop :)

      Jason L. Froebe

      Team Sybase member

      No one has seen what you have seen, and until that happens, we're all going to think that you're nuts. - Jack O'Neil, Stargate SG-1

Re: regex grouping
by GrandFather (Saint) on Nov 02, 2005 at 18:35 UTC

    This would seem to be what you want:

    use strict; use warnings; my $str = "1 2=3 4=5"; print "$str\n"; my @strs = $str =~ m/(\w+=\w+)/g; print "$_\n" foreach @strs;

    Prints:

    1 2=3 4=5 2=3 4=5

    Perl is Huffman encoded by design.