in reply to Regular expression

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:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: Regular expression
by pravakta (Novice) on Oct 29, 2017 at 21:21 UTC

    Thanks AnomalousMonk. Your update problem what very good. I could understand most part of the code but I don't understand what (?i) is used for in "($units =~ m{ (?i) kgs? }xms"

      ... what (?i) is used for ...

      This regex operator turns on case insensitivity until the end of the current matching scope. See  (?adlupimsx-imsx) and  (?^alupimsx) in Extended Patterns. It has the same effect (but with scope control) as the  /i global pattern modifier; see Modifiers. (Both in perlre.) Aside from its scope flexibility, I prefer to use  (?i) rather than the  /i modifier because of its greater general readability.


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

        Thanks for this.