in reply to Extraction of numbers in an string

karls-mac-mini:Desktop karl$ perl -E "say for grep {/\d/} split '', q( +<1,2>:<5,7>:<3,0>);" 1 2 5 7 3 0

It seems like this works. Regards, Karl

«The Crux of the Biscuit is the Apostrophe»

Replies are listed 'Best First'.
Re^2: Extraction of numbers in an string
by AnomalousMonk (Archbishop) on Nov 25, 2016 at 15:44 UTC

    This has a problem with the multi-digit requirement t-rex revealed to us here, and unfortunately there's no simple way to fix it by the use of  \d+ or any other trick I can think of:

    c:\@Work\Perl\monks>perl -wMstrict -le "printf qq{$_ } for grep {/\d/} split '', q(<1,22>:<5,7>:<333,0>); " 1 2 2 5 7 3 3 3 0

    Update: Actually, if one were married to split, it could be made to work with a rather more complex regex:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @d = grep length, split qr{ >:< | [<,>] }xms, q(<1,22>:<5,7>:<333, +0>); dd @d; " (1, 22, 5, 7, 333, 0)
    But I wouldn't recommend it.


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

      Still fairly simple with split:

      #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1176478 use strict; use warnings; my $string = '<1,22>:<5,7>:<333,0>'; my @x = grep /\d/, split /\D+/, $string; print for @x;

        Even simpler: no need for grep.

        my @x = split /\D+/, $string;

        Update: tybalt89 and AnomalousMonk are both right, of course. My bad :(

        Aha! A short, sweet split pattern++. I never thought of that one. But I still prefer  m{ \d+ }xmsg extraction.


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

      "...a problem with the multi-digit requirement"

      Yes. In the moment i clicked on "create" i noticed it. Believe me ;-)

      Best regards, Karl

      «The Crux of the Biscuit is the Apostrophe»