in reply to Regexp for range of numbers

Update: Don't use this. $1 comes from the previous match, not the current one. You would have to use experimental features for a solution in this vein.

This reads a little nicer, but I don't know whether you'd consider it cheating. It's a Perl regex:

/^(\d{1,3})${\($1 > 255 ? qr(^) : qr($))}/
Three digits, then interpolate a scalar ref block that tests what has already matched and returns the rest of the regexp: if the number is too high, the pattern is impossible; otherwise, end-of-string.

Update: meant to link to the post, not the poster. So now "solutions in this vein" links to the post.


Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Regexp for range of numbers
by deibyz (Hermit) on Apr 05, 2005 at 16:21 UTC
    Hey! I've just noticed you're calling me "experimental feature".
    Thanks!! =oD
Re^2: Regexp for range of numbers
by Anonymous Monk on Apr 05, 2005 at 12:42 UTC
    That doesn't work. Interpolation happens before the regex is performed, so your $1 refers to a previous succesful match:
    #!/usr/bin/perl use strict; use warnings; while (<DATA>) { chomp; printf "%d %s\n", $_, /^(\d{1,3})${\($1 > 255 ? qr(^) : qr($))}/ ? "matches" : "fails"; } __DATA__ 3 100 333 200 Use of uninitialized value in numeric gt (>) at XXX line 9, <DATA> lin +e 1. 3 matches 100 matches 333 matches 200 fails
      Yes, I've had a notice to that effect at the top of the post for about an hour.

      Caution: Contents may have been coded under pressure.
        Yeah, I noticed. What happened was that I started writing my reply, was almost finished, called away to put out a fire somewhere, went to lunch, came back, finished my reply, and hit submit.

        The time on top of a node is the time the finished reply reaches the server, not the time someone starts composing. ;-)