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

Good morning, I'm trying to match 2 (+ -)real numbers separated by "to" and then extract and print a range for those numbers. This regex does not extract the second real number properly. Can u help?
#!/usr/bin/perl while (<>) { print if m!(-?\d*?.?\d+)to(-?\d*?.?\d+)!m; print "$1\n$2\n"; print "$_\n" for ($1 .. $2); } giving the result: [barry@localhost]$ ./g 4.5to6.8 4.5to6.8 4.5 6 4 5 6 the "4.5" extracts properly but not the "6.8", it gets truncated to "6"....?

Replies are listed 'Best First'.
Re: Matching two real numbers in a string using regex
by japhy (Canon) on Sep 06, 2002 at 03:13 UTC
    Remove the '?' from the '\d*'. It's making it try to match as few digits as possible. /(-?\d*\.?\d+)to(-?\d*\.\d+)/ will work.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Matching two real numbers in a string using regex
by Silicon Cactus (Scribe) on Sep 06, 2002 at 14:35 UTC
    Why use a regex for this at all, when a simple split will do?
    my($FirstNo, $SecondNo) = split /to/; Much more simple, IMHO.
      Since this would allow wantoeat? to be input? Anyway, for a quick shot you certainly got a point.. ;)
        Right. But without sample input, who's to know if that is likely? <grin>
Re: Matching two real numbers in a string using regex
by Flexx (Pilgrim) on Sep 06, 2002 at 14:42 UTC

    Hi!

    just for fun, I played around with this a little.

    #!/usr/bin/perl while (<>) { print if m/^([+-]?\d*\.\d*)\s+([+-]?\d*.\d*)$/; print "$1 ~ ", int $1, "\n$2 ~ ", int $2, "\n"; print "$_\n" for (int $1 .. int $2); }

    Putting the regex between ^$ makes input like .1 2foo illegal (and would have fixed your regexp, too, BTW). [+-]? allows to have a positive, negative or no sign. So this now takes all of 1 .1 1. 1.1 . all prefixed with + or - or nothing. Note that . is fine -- int converts it to 0.

    int $1 .. int $2 make it work with input like 0.3 4 (where your snipplet was broken).

    The \s+ (one or more whitespace was just because I was annoyed by having to type "to" all the time during playing around. ;)

    Hope you find all that interesting.. ;)

    So long,
    Flexx