I note that each of your test strings has either a single valid number, or a single invalid sequence of digits and dots. What should be the result of, eg, '12.34 and 56.78', or '12.34 on 2004.04.12' or 'on 2004.04.12 found 12.34'?

Your question is also a little unclear in that you ask that the answer be "efficiently" achieved; but "efficient" is a relative term - what counts as "efficient enough"? (Is there a maximum length of strings that must be parsed within whatever limits you set?)

As far as I remember the CUT operator /(?>...)/ is not implemented in a hugely efficient manner, but it may well be sufficient for your needs. You might use that something like:

m{ ^ [^-+\d.]* (?> ( (?# cut and capture) [-+]? (?: \.\d+ | \d+ (?: \. \d* )? ) ) ) (?!\.) }x

This (giving the result in $1) appears to pass your existing tests, and finds "12.34" for my first two additional cases and no match for the third.

Update: on second thoughts, the cut should not be necessary, just need to expand the tailing negative lookahead:

m{ ^ [^-+\d.]* ( [-+]? (?: \.\d+ | \d+ (?: \. \d* )? ) ) (?![.\d]) }x

Note also that the efficiency of CUT is suboptimal mainly when it is being hit repeatedly (eg as part of an alternation in a larger pattern), so it should be fine in this case anyway.

Hugo


In reply to Re: Best practice validating numerics with regex? by hv
in thread Best practice validating numerics with regex? by perlboy_emeritus

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.