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, |
|
|---|
| 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 |