in reply to Match range of number

my ($min, $max) = (35, 50); if ( m/^(\d+)(??{ $^N >= $min && $^N <= $max ? '' : '(?!)'})$/ ){ print "$_ is between $min and $max\n"; }

This uses code assertions, see perlre for details.

Note that this example only works for integers (otherwise you'd have to adapt the regex, preferably with Regexp::Common.)

Replies are listed 'Best First'.
Re^2: Match range of number
by ikegami (Patriarch) on Nov 15, 2007 at 11:59 UTC

    I don't see a reason to invoke the regex compiler for every match.

    if ( m/^(\d+)(?(?{ $^N < $min || $^N > $max })(?!))$/ ){ print "$_ is between $min and $max\n"; }

    $^N was introduced in 5.8. Using $1 would provide backwards compatibility if required.

      $^N was introduced in 5.8. Using $1 would provide backwards compatibility.

      ... at the cost of generality. If you want to use such a snippet multiple times in a regex you have to keep track which capture to use.

      Actually I'm working on a module that generates regexes for matching integers, and that's one of the fallback solutions. When you don't know how your regex will be used, you can't rely on the number of the capture.