in reply to Regexp for range of numbers

TIMTOWTDI, and I wanted to play with (?(condition)true-pattern|false-pattern) asserts.
Looks like this:

my $re =qr/ ^(\d{1,3})$ # Up to 3 digits (?(?{ ($1<256 and $1>=0) }) # If in the correct range .? # An allways match | # Else . # Never going to match after e +nd of string ) /x;

Replies are listed 'Best First'.
Re^2: Regexp for range of numbers
by Roy Johnson (Monsignor) on Apr 05, 2005 at 12:16 UTC
    You don't need to test against zero. Or put anything in the success-pattern; an empty pattern matches just fine.
    /^(\d{1,3})$(?(?{$1<256 }) | . )/x
    or you could move your anchor and use an impossible anchor for the fail-pattern:
    /^(\d{1,3})(?(?{$1<256 }) $ | ^ )/x

    Caution: Contents may have been coded under pressure.
      I tend to use (?!) for the always fail pattern (there are no positions that aren't followed by the empty string). ^ might match if a /m flag is in use, or if the zero-width assertion is done at the beginning of the string. An empty string works fine as an always match pattern - or (?=) if you want to go symmetric.