#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    39
    Rep Power
    1

    Integer range checking using RE


    Hello,
    I have a question regarding integer range checking using regular expressions.
    I want to check if the input number lies between , say 1-5
    I tried doing as follows, but what that gives me is whether each of the characters of the string(my number) lies in that range.As a result, it fails for an input like 125(reports true when it should actually say false)
    Code:
    #!/usr/local/bin/perl
    print "enter number";
    $string = <>;
    
    if($string =~ /([1-5])/)
    {
       print "falls in the range";
    }
    else
    {
       print "does not fall in the range";
    }
    How do I go about this ?
    Thanks.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    163
    Rep Power
    18
    Use anchors ^ and $
    Code:
    if ($string =~ /^[1-5]$/)
    But this is not a fool-proof method. For e.g., if you were to do /^[10-20]$/, this doesn't mean match any number in the range 10 to 20. This simply means match 1 or 0 to 2 or 0.

    By the way, any specific reason why you're choosing regular expressions over the traditional method:
    Code:
    if ($num >= 1 && $num <= 5)
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    779
    Rep Power
    495
    Don't use regex for integer range checking. Just make a numeric comparison with $min and $max.

    But if you really want to use a regex, for your specific case, this would work:

    Perl Code:
    if ($string =~ /^[1-5]$/)


    but only if you have only this number in the line, noting else.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    39
    Rep Power
    1
    Originally Posted by noobie1000
    Code:
    if ($num >= 1 && $num <= 5)
    Originally Posted by Laurent_R
    Don't use regex for integer range checking. Just make a numeric comparison with $min and $max.
    Thanks noobie1000, Laurent_R. Shall remember that and go ahead with the conventional way of using min and max value check.

IMN logo majestic logo threadwatch logo seochat tools logo