#!/usr/bin/env -S perl -w ##!/usr/bin/env -S perl -wd use v5.30.0; use strict; #use re 'debug'; #ues Regexp::Debugger; use Test::More tests => 16; my @strings = ( "today's date 10.13.2023", "The frequency is 10346.87Hz", ); # # This is such an improvement over Friedl pg 194-195... # my $lookAhead = qr/ (?! (?: .*\.){2,}) /x; my $regex = qr/ ^ $lookAhead [+-]? [\d.]+ $/x; # # See: https://stackoverflow.com/questions/22652393/regex-1-variable-reset # From: Brian Foy # # Never, never, never use $& without first testing for TRUE... # See PP pg 781, the use of the word 'successful' :-( # Also see my REinsights.pl for lengthy discussion from Brian Foy re # when and whether $n, $`, $& and $' will be reset after unsuccessful # matches. # for my $str (@strings) { say "\$str => $str"; if ($str =~ / [+-]?[\d.]+ /x) { # Pattern fails without this step; why??? if ($& =~ $regex) { say "matched"; say "\$& => $&" if $&; } else { say "unmatched"; } } else { say "unmatched"; } } sub isFloat { my $case = $_[0]; # say $case->[0], " ", $case->[1]; if ($case->[0] =~ / [+-]?[\d.]+ /x) { # MUST test here to use $& my $try = $&; if ($case->[1] eq 'valid') { like $try, $regex, "trying ${\(sprintf(\"%-27s: \$& => %-13s\", \"\'$case->[0]\'\", $try))} \'$case->[1]\'"; } else { unlike $try, $regex, "trying ${\(sprintf(\"%-27s: \$& => %-13s\", \"\'$case->[0]\'\", $try))} \'$case->[1]\'"; } } else { say "$case->[0] unmatched"; } } 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' ], ); say "\nRunning tests..."; say " with: $regex\n"; say "Testing mixed (valid and invalid) naked and embedded float strings..."; for my $case (@floats) { isFloat($case); }; exit(0); __END__