in reply to Re: regex to capture an unsigned decimal value, but also preserving the user's formatting.
in thread regex to capture an unsigned decimal value, but also preserving the user's formatting.

Hello davido,

Your use of the + (possessive) quantifier is ingenious, as it leads to simple, elegant code. I think you need to backslash the dot to avoid matching any character:

say "$_ => [", (m/(\d*\.?+\d*)/x ? "$1]" : ']'); # ^

But my main quibble is that this doesn’t work consistently if the decimal is embedded in a longer string. (Whether that’s actually a requirement isn’t clear from the OP.) For that, I came up with the following regex, which is verbose but seems to work OK:

#! perl use strict; use warnings; use feature qw( say ); my $decimal = qr{ ( (?: \d+ \.? \d* ) | (?: \d* \.? \d+ ) ) }x; while (<DATA>) { chomp; next unless length; say "$_ => [", (/$decimal/x ? "$1]" : ']'); } __DATA__ 0.12 .12 12. 12 no numbers here abc.def42 .7zx

Output:

16:39 >perl 1621_SoPW.pl 0.12 => [0.12] .12 => [.12] 12. => [12.] 12 => [12] no numbers here => [] abc.def42 => [42] .7zx => [.7] 16:39 >

Cheers,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

  • Comment on Re^2: regex to capture an unsigned decimal value, but also preserve the user's formatting.
  • Select or Download Code

Replies are listed 'Best First'.
Re^3: regex to capture an unsigned decimal value, but also preserve the user's formatting.
by davido (Cardinal) on May 04, 2016 at 15:00 UTC
Re^3: regex to capture an unsigned decimal value, but also preserve the user's formatting.
by AnomalousMonk (Archbishop) on May 04, 2016 at 14:47 UTC

    I think the other important point to make is that the order of the sub-patterns in the ordered alternation is critical:

    c:\@Work\Perl\monks>perl -wMstrict -le "my $ufp = qr{ \d* [.]? \d+ | \d+ [.]? \d* }xms; ;; for my $s (qw(0.12 .34 56. 78)) { printf qq{'$s' -> }; printf qq{'$1' \n} if $s =~ m{ ($ufp) }xms; } ;; my $s = '0.12 -0.98 .34 -.76 56. -54. 78 -32 bla bla abc.def42 .7zx'; printf qq{'$1' } while $s =~ m{ ($ufp) }xmsg; " '0.12' -> '0.12' '.34' -> '.34' '56.' -> '56' '78' -> '78' '0.12' '0.98' '.34' '.76' '56' '54' '78' '32' '42' '.7'
    (See  '56.' and  '-54.' instances.)


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