evert has asked for the wisdom of the Perl Monks concerning the following question:

I have a script that returns the following output:
'All usrloc tests completed successful.
received last message 4.453 ms after first request (test duration).'
What is the proper regex to extract the value (4.453) from this string...? Regards, Evert
  • Comment on How do I extract the value from this string...?

Replies are listed 'Best First'.
Re: How do I extract the value from this string...?
by davido (Cardinal) on Feb 17, 2004 at 16:20 UTC
    m/\s(\d+(?:\.\d+)?)(?:\s*ms)/

    If the match is successful (be sure to check), the numeric value will be in $1.

    This matches one or more numeric digits, followed optionally by a decimal point and one or more digits, followed by an optional space, followed by "ms" (milliseconds). The space-"ms" part is not strictly necessary, but could help if there's a possibility of two sets of numbers ending up in the string somehow, plus IMHO, it can make an RE more human readable if there is some predictable anchor text in there for a human eye to catch.

    Update: Note that this RE will accept numbers that look like "1", or "1.0", but not ".1". I did that on purpose, assuming that "0.1" is how decimal milliseconds would be represented. It wouldn't be too hard to tweak it to accept ".1" as well, but probably unnecessary. This particular RE will also reject numbers that have more than one decimal point (as in 198.60.22.2), which really isn't a number anyway. That too is by design. Oh, and negative numbers aren't accepted. Add an optional hyphen to the beginning if you want them. ;) Enjoy!


    Dave

Re: How do I extract the value from this string...?
by Tomte (Priest) on Feb 17, 2004 at 16:17 UTC

    Have a look at Regexp::Common::number.

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

Re: How do I extract the value from this string...?
by jeffa (Bishop) on Feb 17, 2004 at 16:19 UTC
    Looks like you have a newline in your string, but that shouldn't matter ... i would use a character class that catches 0 through 9 and the dot:
    my $str = "blah blah\nlast message 4.453 ms after\n"; my ($numb) = $str =~ /([0-9.]+)/; print $numb, "\n";

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)