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

 s/ (-? \d+ \.? \d*? ) \-\-? \d+ \.? \d*?/ $1 /

This is supposed to take temperature measurements as a range, and leave only the lower part of it i.e. 25.3-26.5 -> 25.3. The first -? is for negative temperatures, as is the \- in the middle as in: -23--10.2. Decimal points are optional, as is the precision of the decimal.

It works for most of my numbers, but goes nuts with something like 52-52.5 -> 525. It should just leave 52, but tacks the trailing 5 on. Can anyone help explain this, or suggest an alternative superior regexp?


Thanks

Replies are listed 'Best First'.
Re: Misunderstood regexp
by japhy (Canon) on Jul 27, 2004 at 17:34 UTC
    There is no need to match non-greedily on the post-decimal digits: s{ (-? \d+ \.? \d* ) --? \d+ \. \d* }{$1}x should be fine.
    _____________________________________________________
    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
      Thanks very much. It was indeed an unnecessarily stingy expression. Call me paranoid...
Re: Misunderstood regexp
by dragonchild (Archbishop) on Jul 27, 2004 at 17:37 UTC
    Change \d*? to \d* and see if that helps. :-)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

Re: Misunderstood regexp
by Dietz (Curate) on Jul 28, 2004 at 06:48 UTC
    (-?[.\d]+(?!<-)) should help

    $stra = "52-52.5"; $strb = "25.3-26.5"; $strc = "25.3--26.5"; $strd = "-25.3-26.5"; $stre = "-25.3--26.5"; ($str1) = $stra =~ /(-?[.\d]+(?!<-))/; print $str1, $/; ($str1) = $strb =~ /(-?[.\d]+(?!<-))/; print $str1, $/; ($str1) = $strc =~ /(-?[.\d]+(?!<-))/; print $str1, $/; ($str1) = $strd =~ /(-?[.\d]+(?!<-))/; print $str1, $/; ($str1) = $stre =~ /(-?[.\d]+(?!<-))/; print $str1, $/;

    Update: added examples