You can make the dot possessive and the trailing digits greedy but optional:

while(<DATA>){ chomp; next unless length; say "$_ => [", (m/(\d*\.?+\d*)/x ? "$1]" : ']'); } __DATA__ 0.12 .12 12. 12

This yields the following output:

0.12 => [0.12] .12 => [.12] 12. => [12.] 12 => [12]

I do not know what additional edge cases you might encounter that would break this. But for your test cases it works.

Two tricks here. First, it was a mistake to use the + quantifier on the trailing \d, because then it became a required portion of the match. If it's required, then 12. is going to fail to match the decimal point because it comes before the trailing \d+. By making the quantifier * we stay greedy, but optional.

The next trick is the ?+ quantifier for the decimal point. The + here signifies to be possessive -- once it has matched, hold onto what it matched against, and don't give it up during backtracking.

For reference, here are the two regexes (yours and mine) in close proximity. You can disregard the parens here; I'm only using them for capturing, which you were achieving by referring to the match hash.

m/( \d* \.?+ \d* )/x # Mine m/( \d* \.? \d+ )/x # Yours

I suggest walking through your original regular expression, and the one I've provided using the Regexp::Debugger's rxrx utility. I think my inadequate description will be clearer once you see the wheels in motion.

Update: I've fixed the backslashing of the . in the pattern.


Dave


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.