I did some benchmarking of this solution, comparing it to a dumb join '|', 0 .. 255.

Update: and benchmarked mwah's solution as well.

The non-backtracking solution really pays off:

Rate brute_force mwah grinder brute_force 125/s -- -25% -92% mwah 167/s 33% -- -89% grinder 1520/s 1114% 812% --

However demerphq++'s Trie optimization (I hope I remembered the name correctly) in perl5.10 reduced that advantage significantly - so far, that it becomes faster than the code assertions:

Rate mwah brute_force grinder mwah 156/s -- -32% -87% brute_force 229/s 47% -- -81% grinder 1181/s 659% 416% --

Removing the /o-flags from the regexes makes the gap a bit wider.

I used this script for benchmarking:

#!/usr/bin/perl use strict; use warnings; use Benchmark qw(:all); my $grinder = sub { for (0 .. 1000){ if ("$_" =~ m/^(?:2(?:[6-9]|5[0-5]?|[0-4]\d?)?|[3-9]\d?|1(?:\d +\d?)?|0)$/){ if ($_ > 255){ print "Fails for $_\n"; } } else { if ($_ < 255){ print "Fails for $_\n"; } } } }; my $mwah = sub { my $re = qr{ ((?>\d+)) # what to capture, don't backtrack: ( ++?> ) (??{ $1<255 # what is looked for ? '' # if yes, let the regex succeed : '(?!)' # if no, let the regex bail }) }x; for (0 .. 1000){ if ("$_" =~ m/^$re$/){ if ($_ > 255){ print "Fails for $_\n"; } } else { if ($_ < 255){ print "Fails for $_\n"; } } } }; my $bruteforce = sub { my $re = join '|', 0 .. 255; # print $re, "\n"; for (0 .. 1000){ if ("$_" =~ m{^(?:$re)$}){ if ($_ > 255){ print "Brute force Fails for $_\n"; } } else { if ($_ < 255){ print "Brute force Fails for $_\n"; } } } }; cmpthese(-3, { grinder => $grinder, mwah => $mwah, brute_force => $bruteforce, });

In reply to Re^2: does code help regex match numeric ranges? by moritz
in thread does code help regex match numeric ranges? by AlwaysLearning

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.