in reply to Best practice validating numerics with regex?
"I'm looking for an interesting discussion of ways and means"
#!/usr/bin/perl use strict; # https://www.perlmonks.org/?node_id=11154990 use warnings; use feature 'bitwise'; use List::AllUtils qw( reduce ); my @floats = ( [ '0.', 'valid' ], [ '0.007', 'valid' ], [ '.757', 'valid' ], [ '125.89', 'valid' ], [ '+10789.24', 'valid' ], [ '+107894', 'valid' ], [ '-0.0008', 'valid' ], [ 'The temperature is 28.79C', 'valid' ], [ 'Frequency: 10877.45Hz', 'valid' ], [ '255.0.0.0', 'invalid' ], [ '255.aa', 'valid' ], [ "10.13.2023, today's date", 'invalid' ], [ '0.119.255.255' , 'invalid' ], [ 'Date: 10.13.2023 BC', 'invalid' ], [ '-42', 'valid' ], [ '2004.04.12 Friedl nomatch','invalid, Friedl pg 195' ], [ 'all of 12.34 and 3.4.5.6 and 37' ], [ '300 10.16.2023 -42 255.0.0.0 lucky 7' ], ); my $leftside = length reduce {$a |. $b->[0]} @floats; # auto-adjust for my $str ( map $_->[0], @floats ) { my @numbers = grep /./, $str =~ /(?| (?:(?:\d+\.){2,}\d+)() | ([+-]?(?:\d+(?:\.\d*)?|\.\d+)) )/gx; printf "%*s %s\n", $leftside, $str, "@numbers"; }
Outputs:
0. 0. 0.007 0.007 .757 .757 125.89 125.89 +10789.24 +10789.24 +107894 +107894 -0.0008 -0.0008 The temperature is 28.79C 28.79 Frequency: 10877.45Hz 10877.45 255.0.0.0 255.aa 255. 10.13.2023, today's date 0.119.255.255 Date: 10.13.2023 BC -42 -42 2004.04.12 Friedl nomatch all of 12.34 and 3.4.5.6 and 37 12.34 37 300 10.16.2023 -42 255.0.0.0 lucky 7 300 -42 7
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Best practice validating numerics with regex?
by perlboy_emeritus (Scribe) on Oct 17, 2023 at 20:38 UTC | |
by dasgar (Priest) on Oct 17, 2023 at 22:45 UTC | |
by tybalt89 (Monsignor) on Oct 21, 2023 at 13:47 UTC | |
by swl (Prior) on Oct 21, 2023 at 21:43 UTC |