mldvx4 has asked for the wisdom of the Perl Monks concerning the following question:
I am looking to simplify a pattern. If I have a string my $x = "0.01 NaN 2.30 4.44"; then the following pattern finds the items present:
my $r1 = qr/([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)/x;
Notice that the same capture group criteria are repeated. I wonder how I may write that so it is simpler, shorter, and all on one line. Here is some pseudo-code to try to show what I am aiming for: my $r1 = qr/(?=([Na0-9\.\-\+]+)\s+){4}/
However, I've tried that and some permutations without luck:
#!/usr/bin/perl use strict; use warnings; my $x = "0.01 NaN 2.30 4.44"; # the following works as desired my $r1 = qr/([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)\s+ ([Na0-9\.\-\+]+)/x; my ($d, $e, $f, $g) = ($x =~ m/$r1/x ); print qq($d, $e, $f, $g\n); # the following finds the first number twice my $r2 = qr/(?=(([Na0-9\.\-\+]+)\s*)){4}/x; ($d, $e, $f, $g) = ($x =~ m/$r2/x ); print qq($d, $e, $f, $g\n); # the following finds a null prior to the first item my $r3 = qr/((?=([Na0-9\.\-\+]+)\s*){4})/x; ($d, $e, $f, $g) = ($x =~ m/$r3/x ); print qq($d, $e, $f, $g\n); exit(0);
How can I write that pattern so that the pattern it contains is repeated but not locked into the values found in the very first match? Is this a case for using recursive patterns?
|
---|