in reply to Match range of number

You can't do ranges in regexen like that, it just sets up a character class containing 0, 1, 2 and 2. You could set up both ranges in arrays outside the regex and then use the pipe '|' alternation metacharacter.

use strict; use warnings; my @toTest = qw{ X-1Y40 X13Y39 X20Y60 X22Y35 }; my $rxValid = do { local $" = q{|}; my @xRange = ( 0 .. 22 ); my @yRange = ( 35 .. 50 ); qr{(?x) ^ X (?:@xRange) Y (?:@yRange) $}; }; foreach my $test ( @toTest ) { print qq{$test: }, $test =~ $rxValid ? qq{valid\n} : qq{invalid\n}; }

This produces the following.

X-1Y40: invalid X13Y39: valid X20Y60: invalid X22Y35: valid

I hope this is helpful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Match range of number
by ikegami (Patriarch) on Nov 15, 2007 at 11:56 UTC
    Regexp::List should create a very efficient regex in this case.
    use Regexp::List qw( ); my $rxValid = do { my $re_builder = Regexp::List->new(); my $x_range = $re_builder->list2re(0..22); my $y_range = $re_builder->list2re(35..50); qr/ ^ X $x_range Y $y_range $/x; };
      I'd say Regexp::List is surprisingly fast:
      perl bm.pl Rate rxValid plain Regexp::List rxValid 245760/s -- -19% -19% plain 303675/s 24% -- 0% Regexp::List 303675/s 24% 0% --
      --
      Andreas