in reply to Reg Ex to find IP address in range

The trick is to think of sequences of digits, not the number they represent. What options exist for the first digit encountered? What conditions have to be met after a certain one of them?
use strict; use Test::More 'no_plan'; my $rx = qr/\A (?: [0-4]\d? | 5?[0-5] ) \. (?: [0-4]\d? | 5?[0-5] ) \z/x; my %test = ( '56.0' => 0, '0.56' => 0, '48.56' => 0, '56.10' => 0, '55.0' => 1, '55.55' => 1, '0.0' => 1, '10.10' => 1, ); my $result; is(/$rx/, !!$result, $_) while ($_, $result) = each %test; __END__ ok 1 - 0.56 ok 2 - 56.10 ok 3 - 55.0 ok 4 - 55.55 ok 5 - 48.56 ok 6 - 56.0 ok 7 - 10.10 ok 8 - 0.0 1..8

If the first digit seen is any of 0 to 4, then it is legal, and may optionally be followed by any other digit. If it is 5, it is legal, and may optionally be followed by another digit from the 0-5 range. Any other sequence is illegal.

Update: I knew I was missing something when I wrote my test cases.. sigh. And it is so obvious. So there's a third case if the first digit is 6-9: it it is legal if not followed by anything.

my $rx = qr/\A (?: [0-4]\d? | 5?[0-5] | [6-9] ) \. (?: [0-4]\d? | 5?[0-5] | [6-9] ) \z/x;
Adding some cases to the test:
'62.6' => 0, '9.97' => 0, '55.9' => 1, '1.49' => 1, '6.7' => 1, '06.7' => 1,
They all pass. Now let's hope I'm not still a bonehead.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Reg Ex to find IP address in range
by Abigail-II (Bishop) on Aug 28, 2003 at 18:34 UTC
    Your regex fails on for instance "7.8".

    Abigail