The regex  /^(?<weight>\d+)\s*$/ is "anchored" to both the start and end of a string and would match something | only something like  '123  ' (I think — untested | I know — tested), which appears nowhere in your  $x string. Try something like:

c:\@Work\Perl\monks>perl -wMstrict -le "my $x = '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15'; print qq{'$x'}; ;; printf qq{'$+{weight}' } while $x =~ m{ (?<weight> \d+) }xmsg; " '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15' '1' '2' '3' '4' '5' '6' '7' '8' '9' '10' '11' '12' '13' '14' '15'
(Update: You were print-ing  $+{weight} regardless of whether or not there had been a match!)

Update: A slightly different problem and approach:

c:\@Work\Perl\monks>perl -wMstrict -le "my $rx_weight = qr{ (?<! \d) \d+ (?! \d) } +xms; my $rx_units = qr{ (?<! [[:alpha:]]) [[:alpha:]]+ (?! [[:alpha:]]) } +xms; ;; my $x = '12 lbs 234 kgs 567 groats foo42kg7lb'; print qq{'$x'}; ;; while ($x =~ m{ \G .*? (?<weight> $rx_weight) \s* (?<units> $rx_units) }xmsg ) { my ($weight, $units) = @+{ qw(weight units) }; print qq{for debug: got '$weight' '$units'}; if ($units =~ m{ (?i) kgs? }xms) { print qq{metric: $weight}; } elsif ($units =~ m{ (?i) lbs? }xms) { print qq{English: $weight}; } else { print qq{unknown units '$units': $weight}; } } " '12 lbs 234 kgs 567 groats foo42kg7lb' for debug: got '12' 'lbs' English: 12 for debug: got '234' 'kgs' metric: 234 for debug: got '567' 'groats' unknown units 'groats': 567 for debug: got '42' 'kg' metric: 42 for debug: got '7' 'lb' English: 7
Please see perlre, perlretut, and perlrequick.


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


In reply to Re: Regular expression by AnomalousMonk
in thread Regular expression by pravakta

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.